Get current date time from server and convert it into local time in c#

元气小坏坏 提交于 2019-12-03 16:59:55
mohsen dorparasti

no need to know server time zone. if the server time setting is correct you can try this :

DateTime serverTime = DateTime.Now; // gives you current Time in server timeZone
DateTime utcTime = serverTime.ToUniversalTime(); // convert it to Utc using timezone setting of server computer

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi); // convert from utc to local

to check it locally , change your computer timezone to match your server. then run the code. I check and it's working fine.

update:

the first two lines can be mixed into one line as below . that has a better performance :

DateTime utcTime = DateTime.UtcNow;

if you want to add 12 Hours and 30 minutes to your Server time to get equavalent localtime(assuming you have server time), you can use AddHours() and AddMinutes() functions to add the 12:30 hours

Try This:

DateTime dt= /*your server time*/;
dt=dt.AddHours(12);
dt=dt.AddMinutes(30);

If your server's clock is set correctly (regardless of time zone), then the first three lines of your own code are exactly correct. The result variable contains the local time in the India time zone.

Simply omit the last two lines.

So you have the server's time, and you know the server's time zone? Then you can get the local time like this:

//Server: 09-Mar-2014 11:00:00 AM:
var serverTime = new DateTime(2014, 3, 9, 11, 00, 00);

var serverZone = TimeZoneInfo.FindSystemTimeZoneById("US Mountain Standard Time");
var localZone = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

var localTime = TimeZoneInfo.ConvertTime(serverTime, serverZone, localZone);
// => 09-Mar-2014 11:30:00 PM
Sudarshan Kate
 DateTime serverTime = DateTime.Now;

 DateTime utcTime = serverTime.ToUniversalTime(); 

// convert it to Utc using timezone setting of server computer

 TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");

 DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi); 

// convert from utc to local

The simplest way to get the UTC date and time of the server is (SELECT GETUTCDATE();). Try it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!