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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With