8

In .Net Core 2 -

Is there a way to set the application's timezone globally so that whenever I request for DateTime.Now I'll get the current time for a timezone I want (lets say GMT+3) instead of the time of the server where the application is hosted?

I figured a good place to have a configuration providing this would be the Startup.cs file, but my search queries gets me nowhere with this.

shahaf
  • 669
  • 1
  • 8
  • 25

3 Answers3

8

You can use TimeZoneInfo for this

DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "Eastern Standard Time");

Replace with the desired time zone.

  • 5
    Be careful with cross-platform issues: https://devblogs.microsoft.com/dotnet/cross-platform-time-zones-with-net-core/ – JustAMartin Oct 23 '19 at 12:49
4

No.

DateTime.Now always returns the time in the system's local time zone.

Matt Johnson-Pint
  • 214,338
  • 71
  • 421
  • 539
-3

one way to achieve this is to have a wrapper to request for the current date time, something like

public static class MyTimeZone
{
    public static DateTime Now => DateTime.UtcNow.AddHours(3);
}

and you can just request for the time like this

MyTimeZone.Now

If the timezone is dynamic, just change it to a function.

public static class MyTimeZone
{
    public static DateTime Now(int offset) => DateTime.UtcNow.AddHours(offset);
}
mylee
  • 1,175
  • 1
  • 7
  • 10
  • 1
    If you're going to add hours, you also need to call `SpecifyKind` to set the kind to `Unspecified`. Otherwise, the value will be treated as UTC by any APIs that look at `.Kind`. A better idea is to use `TimeZoneInfo.ConvertTime`, and/or use a `DateTimeOffset`, possibly with `.ToOffset` – Matt Johnson-Pint Feb 21 '19 at 21:18
  • 1
    You can’t hardcore Timezone shift, because it could change due to Daylight Saving Time – Michael Freidgeim May 26 '19 at 22:47