问题描述
帮助:我有是有在GMT-07.00小时时间的服务器。我的本地时间为GMT +05.30小时。我需要从服务器获取当前日期和时间,此日期和时间转换成我的本地时间。我试过很多代码,但仍没有找到这样的连续方式。 。有人可以请帮我
Help: I have a server which is having time in GMT-07.00 hours. My local time is GMT+05.30 hours. I need to get current date and time from server and convert this date and time into my local time. I have tried many codes, but still have not found a successive way of doing this. Can somebody please help me out.
string zoneId = "India Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, tzi);
DateTime cu = result.ToUniversalTime();
DateTime cur = cu.ToLocalTime();
我已经尝试了所有上面的方法,我依然没有得到正确的答案。假如我目前的本地时间为09月2014年下午12时51分零零秒,然后我的服务器时间会从我的本地时间12.30小时不同,即减去12小时,从我的本地时间30分钟,得到我的服务器时间。我需要从服务器时间让我的本地时间。怎样才可以acheived?请建议我一些解决办法..预先感谢您的回答
I have tried all the above methods, still I'm not getting the correct answer. Suppose my current local time is 09-Mar-2014 12:51:00 PM, then my server time would be 12.30 hours different from my local time, ie subtract 12 hours and 30 minutes from my local time to get my server time. I need to get my local time from the server time. How can it be acheived?? Please suggest me some solutions.. Thanks in advance for your answers
推荐答案
不需要知道服务器的时区。如果服务器的时间设置是正确的,你可以试试这个:
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;
这篇关于从服务器获取当前日期时间,并将其转换为本地时间在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!