Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 representation, 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.

like image 217
Kees C. Bakker Avatar asked Jan 13 '11 16:01

Kees C. Bakker


People also ask

What is parse date time?

The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.


1 Answers

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

like image 69
Brian Behm Avatar answered Oct 11 '22 04:10

Brian Behm