Changing DATETIMEOFFSET Values globally across the application using culture in C# & ASP.NET MVC5

39 views Asked by At

I have an ASP.NET MVC 5 application that requires to display all datetimeoffset values in a specific timezone according to the logged in user location.

Is there a way to set the culture for the entire application, eg.. en-us, en-GB, en-AU etc. when it loads, and display all datetimeoffset values according to the timezone of the culture setting?

Thanks in advance!

1

There are 1 answers

2
Matt Johnson-Pint On

No, because culture and time zone are orthogonal concepts. For example, I might be an English speaking person from New York, but I might be visiting or working in Japan. If I want my clock to represent local time, I'd set the computer's time zone zone to Asia/Tokyo (Mac/Linux) or Japan Standard Time (Windows), even though my culture settings would still be en-US.

In other words, while .NET does have a way to set culture globally for an application (ie. CultureInfo.CurrentCulture), time zone is not a part of the culture data.

As of latest .NET 8, there is no mechanism for setting time zone globally - at least not for the values that are returned from DateTime.Now, DateTimeOffset.Now, and TimeZoneInfo.Local.

However, .NET 8 introduced the TimeProvider class, which you can read about here. Using the example shown there, you can create yourself a ZonedTimeProvider and set a particular time zone. Then in your app, when getting the current time, get it from the provider instead. The benefit is that you can substitute different providers when running unit tests, or when running in the application in different time zones.

Of course, there's always the traditional way: Get the UTC time, and convert it to specific time zones as needed using TimeZoneInfo.ConvertTime.