简体   繁体   中英

How get correct time zone offset on daylight saving in C#

I am struggling to get a correct datetimeoffset when switching from winter to summer time.

What I am trying to do is to send a request to an API, and the parameters are two dates with following format:" 2018-03-01T01:00:00+01:00 " I have created two Datetimeoffset in Paris TimeZone (my PC is in the UK but the API is a french service), here is how I did this:

var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Romance Standard Time");
DateTime dt = new DateTime(2018,03,01,00,00,00);
dt = DateTime.SpecifyKind(dt, DateTimeKind.Local);
DateTimeOffset startingDate = new DateTimeOffset(dt);
startingDate = TimeZoneInfo.ConvertTime(startingDate, timeZoneInfo);
DateTimeOffset endingDate = new DateTimeOffset();
for (int i = 0;i<700;i++)
{
     startingDate = startingDate.AddMonths(i);
     endingDate = startingDate.AddMonths(1);
     IRestResponse myquery= getAPIresult("", "", startingDate.ToString("yyyy-MM-ddTHH:mm:sszzzzzz"), endingDate.ToString("yyyy-MM-ddTHH:mm:sszzzzzz"));

When executing the code, I get " 2018-03-01T01:00:00+01:00 " for startingDate, which is what I expect.

But I get " 2018-04-01T01:00:00+01:00 " for endingDate, which is strange as the 31st of March is the daylight saving in France, so the Paris timeZone such from GMT+01 to GMT+02.

So I should get " 2018-04-01T01:00:00+02:00 " for ending date.

If you could help me on this, I would really be thankfull.

You must call TimeZoneInfo.ConvertTime within the loop, such that every value is re-evaluated against the time zone. (The DateTimeOffset caries only the offset, not the time zone.)

Also, your logic of .AddMonths(i) is in error, as you are mutating the startingDate in the loop. You can either use .AddMonths(1) , or you can hold the original starting date in a separate variable that doesn't mutate.

The simplest fix is thus:

startingDate = TimeZoneInfo.ConvertTime(startingDate.AddMonths(1), timeZoneInfo);
endingDate = TimeZoneInfo.ConvertTime(startingDate.AddMonths(1), timeZoneInfo);

Additionally, you might want to think about why you're introducing DateTimeKind.Local in the starting date at all. It should be irrelevant for this task. Consider perhaps instead:

DateTime dt = new DateTime(2018, 3, 1, 0, 0, 0);
TimeSpan offset = timeZoneInfo.GetUtcOffset(dt);
DateTimeOffset startingDate = new DateTimeOffset(dt, offset);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM