Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get timezone from DateTime

Does the .Net DateTime contain information about time zone where it was created?

I have a library parsing DateTime from a format that has "+zz" at the end, and while it parses correctly and adjusts a local time, I need to get what the specific time zone was from the DateTime object.

Is this possible at all? All I can see is DateTime.Kind, which specifies if time is local or UTC.

like image 709
dbkk Avatar asked Feb 23 '09 06:02

dbkk


People also ask

How do I get the timezone from datetime?

How to Get the Current Time of a Timezone with datetime. You can get the current time in a particular timezone by using the datetime module with another module called pytz . You can then check for all available timezones with the snippet below: from datetime import datetime import pytz zones = pytz.

How do I know if datetime has timezone?

A timezone's offset refers to how many hours the timezone is from Coordinated Universal Time (UTC). A naive datetime object contains no timezone information. The easiest way to tell if a datetime object is naive is by checking tzinfo. tzinfo will be set to None of the object is naive.

What timezone is datetime NOW ()?

The property UtcNow of the DateTime class returns the current date and time of the machine running the code, expressed in UTC format. UTC is a universal format to represent date and time as an alternative to local time. Also known as the GMT+00 timezone.


1 Answers

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.

DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.

The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.

EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)

like image 144
Jon Skeet Avatar answered Oct 11 '22 12:10

Jon Skeet