What is wrong with the following DateTime/TimeZone sample?
The following code:
var dateTime1 = DateTime.Now;
var str = dateTime1.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
var dateTime2 = dateTime1.ToUniversalTime();
str = dateTime2.ToString("dd-MMM-yyyy HH:mm:ss");
Console.WriteLine(str);
var dateTime3 = TimeZoneInfo.ConvertTimeFromUtc(dateTime2, TimeZoneInfo.Local);
str = date开发者_StackOverflow中文版Time3.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
prints as excepted:
18-Feb-2010 09:07:06-05:00
18-Feb-2010 14:07:06 18-Feb-2010 09:07:06-05:00
On the other hand the code:
var dateTime1 = DateTime.ParseExact("20090615013505-0400", "yyyyMMddHHmmsszzz",null);
var str = dateTime1.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
var dateTime2 = dateTime1.ToUniversalTime();
str = dateTime2.ToString("dd-MMM-yyyy HH:mm:ss");
Console.WriteLine(str);
var dateTime3 = TimeZoneInfo.ConvertTimeFromUtc(dateTime2, TimeZoneInfo.Local);
str = dateTime3.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
prints this:
15-Jun-2009 01:35:05-04:00
15-Jun-2009 05:35:05 15-Jun-2009 01:35:05-04:00
I expected the last line to be 15-Jun-2009 00:35-05:00
since the local time zone is GMT-05:00.
What am I missing here?
One example is in February (when daylight savings is off), and one in June (when daylight savings time is in effect.)
Since UTC doesn't change, your offset will be one hour less during Daylight Savings. (By your offset, it looks like you're in Eastern Standard/Eastern Daylight time).
DateTime instances don't have any concept of what time zone they are in. From the MS help for custom date time format strings:
For this reason, the z format specifier is not recommended for use with DateTime values.
Try using a DateTimeOffset instead:
var dateTime1 = DateTimeOffset.ParseExact("20090615013505-0400", "yyyyMMddHHmmsszzz", null);
var str = dateTime1.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
var dateTime2 = dateTime1.ToUniversalTime();
str = dateTime2.ToString("dd-MMM-yyyy HH:mm:ss");
Console.WriteLine(str);
var dateTime3 = dateTime2.ToLocalTime();
str = dateTime3.ToString("dd-MMM-yyyy HH:mm:sszzz");
Console.WriteLine(str);
The dateTime1 is getting the current culture settings, so when it is converted to UTC then back it will still be in local time.
精彩评论