Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does DateTime.TryParseExact() return different time zone for these input strings?

I have the simplest method that parses a string to a DateTime but the return type is DateTimeOffset?.

I expected the output to be

2011-01-11 00:00:00 +01:00
2011-10-11 00:00:00 +01:00

but instead it is

2011-01-11 00:00:00 +01:00
2011-10-11 00:00:00 +02:00

Why do I get this behavior? My test program is below.

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Parse("20110111").ToString());
        Console.WriteLine(Parse("20111011").ToString());
        Console.ReadLine();
    }

    public static DateTimeOffset? Parse(string date)
    {
        DateTime parsedDate;
        if (DateTime.TryParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate))
        {
            return parsedDate;
        }

        return null;
    }
}
like image 765
Anton Avatar asked Jan 19 '26 15:01

Anton


1 Answers

It is returning TimeZone for the current machine and the difference of one hour is due to day light savings. Which are not in effect in October , but they are in January.

like image 159
Habib Avatar answered Jan 21 '26 04:01

Habib