0

How do I get the current date and time in the local timezone? System.DateTime.Now returns the current date and time for what the local time zone was when the program was started, which does the wrong thing.

Duplicate of sum of:

.NET DateTime.Now returns incorrect time when time zone is changed

C# event to detect Daylight Saving or even manual time change

Community
  • 1
  • 1
Joshua
  • 40,822
  • 8
  • 72
  • 132
  • It is important to note that this turns out to be true in up through .NET 3.5. The behavior was changed in .NET 4.0 to get the current time zone on DateTime.Now. – Joshua Jul 31 '15 at 02:36

1 Answers1

-1

You could use the code below if you know which local time zone you're targetting

    DateTime timeUtc = DateTime.UtcNow;
    try
    {
     TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
     DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
     Console.WriteLine("The date and time are {0} {1}.", 
                 cstTime, 
                 cstZone.IsDaylightSavingTime(cstTime) ?
                         cstZone.DaylightName : cstZone.StandardName);
    }
    catch (TimeZoneNotFoundException)
   {
     Console.WriteLine("The registry does not define the Central Standard Time zone.");
   }                           
   catch (InvalidTimeZoneException)
  {
     Console.WriteLine("Registry data on the Central STandard Time zone has been corrupted.");
   }

For more info https://msdn.microsoft.com/en-us/library/bb397769(v=vs.110).aspx

Fred Rogers
  • 413
  • 2
  • 8
  • 19