Search code examples
asp.net-coredatetimedst

.net core converting from utc time to my local time and also taking into consideration daylight savings time


I am currently storing date and time in a database using UTC and was wondering if .net core automatically calculates for daylight savings time switching or do I have to manually implement that in my code based on the day that the time shifts in the specific countries?

I need the database to convert the UTC time in the database to Toronto, Ontario's current date and time.


Solution

  • According to your description, I suggest you could try to use the TimeZoneInfo.ConvertTimeFromUtc method to convert the UTC time to Toronto time.

    Details ,you could refer to below codes:

      // your datadbase UTC  time
            DateTime utcTime = DateTime.UtcNow;
    
            //time zone  for Toronto
            TimeZoneInfo torontoTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    
            // convert the UTC time to Toronto time
            DateTime torontoTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, torontoTimeZone);