Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring DST (Daylight Saving Time) in .NET

Tags:

c#

.net

dst

I am trying to convert a String to a Datetime object without it modifying it and adding an extra hour/offset to the Datetime object.

This is the code:

string dateStr = "2011-03-18T12:07:00.000+10:00"; //Convert this string to datetime AS IS

DateTime date = Convert.ToDateTime(dateStr);

Console.WriteLine("Original string: " + dateStr);
Console.WriteLine("date toString:   " + date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"));

The output:

Original string: 2011-03-18T12:07:00.000+10:00
date toString:   2011-03-18T13:07:00.000+11:00

If anyone can point how I can ignore DST or simply even convert the date back to what I want as a Datetime object, that would be much appreciated.

Going down the path of modifying the datetime: I have tried to convert the Datetime back but I cannot work out how to change the timezone in the Datetime object and when I use a DatetimeOffset object to do this work, when I call the DatetimeOffset.Datetime it returns the Datetime without the offset

like image 245
Eiji Avatar asked Nov 04 '22 16:11

Eiji


1 Answers

A DateTime object doesn't contain a time zone. It only contains a Kind, which can be Utc, Local, or Unspecified.

When calling Convert.ToDateTime, if any offset is present, that offset will be applied and then the value will be converted to the local time zone. That is - the time zone where the code is running.

Then, by using K in the output format, it returns the offset of the local time zone for that particular date.

To handle this scenario correctly, use the DateTimeOffset type:

string dateStr = "2011-03-18T12:07:00.000+10:00";

DateTimeOffset dto = DateTimeOffset.Parse(dateStr);

Console.WriteLine("Original string: " + dateStr);
Console.WriteLine("dto toString:    " + dto.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffK"));

Regarding your statement:

when I call the DatetimeOffset.Datetime it returns the Datetime without the offset

That is correct. Only the DateTimeOffset type has an offset to return. The DateTime object can only return the local offset of the machine, or zero for a DateTime with DateTimeKind.Utc.

like image 157
Matt Johnson-Pint Avatar answered Nov 14 '22 21:11

Matt Johnson-Pint