简体   繁体   中英

How to parse the date and time depends upon the time zone?

I want to parse the string to time.

string inputDate = "1970-01-01T00:00:00+0000"; 
var dt = DateTime.Parse(inputDate, CultureInfo.InvariantCulture);  
Console.WriteLine("Date==> " + dt);

It is working fine in india time( UTC +5.30 ).

But when I change the time zone to UTC -5 in settings in emulator, the out put is showing

12/31/1969 7:00:00 PM

The date should be same when ever i change the time zone in settings. Please help me to resolve my problem.

Let me explain what is going on here..

Usually , DateTime.Parse method returned DateTime 's Kind property will be Unspecified .

But since your string has time zone information and you using DateTime.Parse method without DateTimeStyles overload (it uses DateTimeStyles.None by default), your DateTime 's Kind property will be Local .

That's why when you use your code in UTC +05.30 time zone system, it will be generate a result like;

01/01/1970 05:00:00 AM

and when you use in UTC -05.00 time zone system, it will generate;

12/31/1969 7:00:00 PM // which is equal 12/31/1969 19:00:00 AM representation

which is too normal.

The date should be same when ever i change the time zone in settings.

Makind your DateTime as UTC is the best choice in such a case. Using ToUniversalTime() method is one way to do that in a Local time.

From documentation;

The Coordinated Universal Time (UTC) is equal to the local time minus the UTC offset.

Since your code generates Local time, your ToUniversalTime() generated datetime's will be the same in both time zone.

Another way to do it, using DateTimeStyles.AdjustToUniversal as a third parameter in DateTime.Parse method.

From documentation;

Date and time are returned as a Coordinated Universal Time (UTC). If the input string denotes a local time, through a time zone specifier or AssumeLocal, the date and time are converted from the local time to UTC . If the input string denotes a UTC time, through a time zone specifier or AssumeUniversal, no conversion occurs. If the input string does not denote a local or UTC time, no conversion occurs and the resulting Kind property is Unspecified.

string inputDate = "1970-01-01T00:00:00+0000";
var dt = DateTime.Parse(inputDate,
                        CultureInfo.InvariantCulture,
                        DateTimeStyles.AdjustToUniversal);

That will generate 01/01/1970 00:00:00 which Kind is Utc .

Final Solution

string givenDate = ("1970-01-01T00:00:00+0000");
DateTime d = DateTime.Parse(givenDate, System.Globalization.CultureInfo.InvariantCulture);
string ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt",  System.Globalization.CultureInfo.InvariantCulture);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM