Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DateTime For Another Time Zone Regardless of Local Time Zone

Regardless of what the user's local time zone is set to, using C# (.NET 2.0) I need to determine the time (DateTime object) in the Eastern time zone.

I know about these methods but there doesn't seem to be an obvious way to get a DateTime object for a different time zone than what the user is in.

 DateTime.Now  DateTime.UtcNow  TimeZone.CurrentTimeZone 

Of course, the solution needs to be daylight savings time aware.

like image 957
Dave Avatar asked Jan 13 '09 22:01

Dave


People also ask

How do I convert a date to a different time zone?

To convert a date to another time zone: Use the toLocaleString() method to get a string that represents the date according to the provided time zone. Pass the result to the Date() constructor. The returned Date object will have its date and time set according to the provided time zone.

How do I convert one time zone to another in C#?

ConvertTime(DateTimeOffset, TimeZoneInfo) method that performs time zone conversions with ToOffset(TimeSpan) values. The method's parameters are a DateTimeOffset value and a reference to the time zone to which the time is to be converted. The method call returns a DateTimeOffset value.

What is a datetime offset?

The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.


1 Answers

In .NET 3.5, there is TimeZoneInfo, which provides a lot of functionality in this area; 2.0SP1 has DateTimeOffset, but this is much more limited.

Getting UtcNow and adding a fixed offset is part of the job, but isn't DST-aware.

So in 3.5 I think you can do something like:

DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(     DateTime.UtcNow, "Eastern Standard Time"); 

But this simply doesn't exist in 2.0; sorry.

like image 90
Marc Gravell Avatar answered Sep 20 '22 06:09

Marc Gravell