Changing the time zone and daylight saving time

We have a scheduler application. Using this application, the user can schedule the task to be completed on 8 AM PT daily for the next 30 days. We convert time to UTC and save it in the database, since we have users from different time zones. We use the following function to convert time to UTC:

public static DateTime ToAccountLocalTime(this DateTime dt) { return TimeZoneInfo.ConvertTimeFromUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("user time zone")); } 

Now, if the user has scheduled the task from 8:00 to 00 every day for the next 30 days from November 1, 2012, then 30 entries will be made in the database for each of 30 days with a time set at 16:00 UTC (as returned by the method above).

The problem arose on November 4, when summer time ended. The task started at 7 a.m. instead of 8 a.m., since the scheduler service runs all the time based on UTC.

To solve this problem, we need the above method to return UTC at 16:00 for dates from November 1 to November 3 and 3 hours UTC for dates after November 4. What changes should I make to achieve this?

+4
source share
2 answers

If local time is important, I would save the local time + time zone and convert it to UTC when you need UTC.

Then you save 8AM PT, and it will convert to 3 or 4 PM UTC depending on whether it is currently DST.

The problem you are facing depends on your database; it may not support time zones. I would probably save the string you passed to FindSystemTimeZoneById . If you want a fantasy, you can create a table that lists all those that have an identifier column and save the identifier.

0
source

You need to do the conversion for each of the 30 days, so ToUtc is ToUtc (or something else, the opposite of the procedure that you inserted in the question) for each of localDate.AddDays(n) , n = 1 .. 30 and save these results .

If ToUtc is defined as:

 return TimeZoneInfo.ConvertTimeToUtc(dt, TimeZoneInfo.FindSystemTimeZoneById("user time zone")); 

it must serve the DST at the specified time. (Be careful with exceptions for ambiguous or invalid times.)

0
source

Source: https://habr.com/ru/post/1445518/


All Articles