How to convert UTC + 0 Date to PST Date?

I have this UTC + 0 Date:

2011-11-28T07:21:41.000Z 

and I would like in C # to convert it to a PST date. How can I do it? Tried using:

 object.Data.ToLocalTime() 

but I can not get the correct value (which should be 2011-11-27)

EDIT

Also tried (after a suggestion on another topic):

 DateTime convertedDate = DateTime.SpecifyKind( DateTime.Parse(object.Data.ToShortDateString()), DateTimeKind.Utc); DateTime dt = convertedDate.ToLocalTime(); string dataVideo = dt.ToShortDateString(); 

but the date is still 11/28/2011 and not 11/27/2011

+7
source share
2 answers

I changed my watch to use UTC-08:00 Pacific Time .

 DateTime timestamp = DateTime.Parse("2011-11-28T07:21:41.000Z"); Console.WriteLine("UTC: " + timestamp.ToUniversalTime()); Console.WriteLine("PST: " + timestamp.ToLocalTime()); 

Output:

 UTC: 28/11/2011 7:21:41 PST: 27/11/2011 23:21:41 

Example with TimeZoneInfo

 DateTime timestamp = DateTime.Parse("2011-11-28T07:21:41.000Z"); Console.WriteLine("UTC: " + timestamp.ToUniversalTime()); Console.WriteLine("GMT+1: " + timestamp.ToLocalTime()); Console.WriteLine("PST: " + TimeZoneInfo.ConvertTimeBySystemTimeZoneId(timestamp, "Pacific Standard Time")); 

Output:

 UTC: 28/11/2011 7:21:41 GMT+1: 28/11/2011 8:21:41 PST: 27/11/2011 23:21:41 
+11
source

For a bit more color

2011-11-28T07:21:41.000Z

This is an ISO8601 timestamp, Z at the end means UTC. This is a concrete example in time.

DateTime.Parse will return the local date time structure to you; there are three types of datetime, UTC, Local, and Unspecified types.

If you try to display this, it will show you that instant in your current time zone of your computers (I am eastern, so when I print it, I get 11/28/2011 2:21:41 AM ).

If I want to switch this DateTime Kind to UTC, I could do something like

DateTime.Parse("2011-11-28T07:21:41.000Z").ToUniversalTime()

Print it now (since now it is a kind of UTC) I get 11/28/2011 7:21:41 AM .

Note that although the time is printed differently, both of these dates indicate the same point in time.

To display this point in a different time zone, the easiest way is to use the TimeZoneInfo class (although I'm not sure if it is 100% accurate).

TimeZoneInfo.ConverTimeBySystemTimeZoneId(dateTime, "Pacific Standard Time").

Printing will now give the desired result 11/27/2011 11:21:41 PM

Please note that this returnTime Kind property is now Unspecified , which means that you cannot transfer it back to UTC without additional information. You no longer have a certain point in time, rather you have an indefinite time ... we know it at the same moment as before, only in peacetime, but the computer no longer knows this. Keep this in mind if you want to save this time.

+1
source

All Articles