开发者

The DateTime.Parse is off by one hour. Why?

I've been having some trouble understanding why the value of a restored date time string differs from its original. I'm writing the string to universal datetime (format "u" so it has a 'z' at the end), but when it is restored, it differs by one hour. I'm using the "u" to prevent this kind of stuff from happening. Can anybody tell me why it differs?

I need a good string repres开发者_高级运维entation, because I'll use the code in 5 different time-zones.

The program:

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfoByIetfLanguageTag("es-CR");

            DateTime min = DateTime.MinValue;

            Console.Write("Min value date: ");
            Console.WriteLine(min);

            Console.Write("String:         ");
            string str = min.ToString("u");
            Console.WriteLine(str);

            DateTime dt = DateTime.Parse(str);

            Console.Write("Restored Date:  ");
            Console.WriteLine(dt);

            Console.ReadLine();

        }
    }
}

The output is:

Min value date: 01/01/0001 12:00:00 a.m.

String: 0001-01-01 00:00:00Z

Restored Date: 01/01/0001 01:00:00 a.m.

Edit: option to try Costa Rica culture.


When you parse the universal DateTime string it is using your local timezone? You can use the methods ToUniversalTime() and ToLocalTime() to convert back and forth. Also, if you place the timezone offset after the "Z" that will help you convert to the right timezone.

Brian


There is a very interesting thread about this on bytes.com.

Il looks like the 'Z' at the end of your date is messing between UTC and CET.

In the very spread area CET it is now (Not Summer Time) exactly one our later then in UTC/GMT/ZULU/Military.

I'm not very confident with this subject, so I let you read the thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜