Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem with time
My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time. How can I do that?

I try this

Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;

and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2. Is there another way of doing this - a simpler way of doing it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
556 views
Welcome To Ask or Share your Answers For Others

1 Answer

The only way you should do it is as follows:

string zoneId = "Central European Standard Time";
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
DateTime result = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow,tzi);
Console.WriteLine("Time is " + result + " in Denmark");

Using the TimeZoneInfo class is the only reliable way in .Net to convert to/from different timezones AND get proper DST conversions.

TimeZoneInfo.ConvertTimeToUtc(dtLocal,tzi) is the reverse converting from a local time to a utc time.


For the TimeZone Id strings, you can run the bit of code here...

foreach( var tz in TimeZoneInfo.GetSystemTimeZones() )
{
    Console.WriteLine(tz.DisplayName + " is Id=','" + tz.Id + "'");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...