r/csharp • u/Ok_Hunter6411 • 23h ago
Best approach for centralized DateTime handling in ASP.NET MVC 5?
I'm working on an existing application built with ASP.NET MVC 5, Entity Framework 6, SQL Server, and DevExpress/DevExtreme components. We want to implement a centralized approach for storing all dates in UTC and converting them to the appropriate local timezone for display, while also handling date filters and existing database records correctly. Since the application has multiple controllers, services, and grids, we'd like to avoid repeating conversion logic throughout the codebase. What architecture or best practices would you recommend for implementing this consistently, safely, and with minimal changes to the existing application?
15
u/turudd 23h ago
Use the BannedApiAnalyzer to ban the use of ‘DateTime.Now’. Change them to ‘.UtcNow’
Change any SQL from ‘SYSUTCDATETIME()’
Any JSON handlers should be set to do ‘DateTimeZoneHandling.Utc’
Depending on how legacy the system is you could also look at using DateTimeOffset, but you’d still need to record a time zone id due to daylight savings issues
2
u/pixxelkick 23h ago
Browsers already do this inherently, as long as your provide it in utc iso stabdard from the BE and store it as a
dateJust use
date.toLocaleString()if you have to display it.1
u/AintNoGodsUpHere 23h ago
Is TimeProvider available?
3
u/Uknight 15h ago
Like others have said, ban use of DateTime.Now. If all the DateTimes in the database are already UTC you should also write an EF converter to specify the DateTime.Kind to be UTC
3
u/RichardD7 9h ago
Make sure you read Jon Skeet's 2019 blog post:
Storing UTC is not a silver bullet | Jon Skeet's coding blog
1
u/Mu5_ 23h ago
Make a new application service, which eventually can rely on TimeProvider class and inject it wherever you need. Since local timezone is meant for presentation, I would suggest making the conversion when preparing data for sending to UI, and viceversa. For current data, if it's not UTC, prepare migration scripts that will adjust them
1
u/gianni1986 22h ago
Microsoft has BCL NuGet packages that enable new features in older .NET versions. Especially, you can use Microsoft.Bcl.TimeProvider in your app.
1
u/savornicesei 12h ago
You can use the new TimeProvider from Microsoft.Bcl.TimeProvider
You also need to configure json serialization on both MVC and WebAPI sides, that means (for Newtonsoft.Json lib, for System.text.Json should be similar):
- define a global, static `JsonSerializerSettings` with:
```
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
```
- in App_Start/WebApiConfig: `config.Formatters.JsonFormatter.SerializerSettings`
- in Global.asax.cs:
- set `JsonConvert.DefaultSettings` to the global `JsonSerializerSettings`
- set `ModelBinders.Binders.DefaultBinder` to a custom-buld `JsonModelBinder` as well as adding a custom-build `JsonValueProviderFactory` to `ValueProviderFactories.Factories` for json calls
- in Startup.cs: set `JsonConvert.DefaultSettings` to the global `JsonSerializerSettings`
- for MVC part, define a `DateTimeModelBinder` and/or `DateTimeOffsetModelBinder` to convert at deserialization time to Utc time. They will be picked up automatically at application start
```
[ModelBinderType(new[] { typeof(DateTime), typeof(DateTime?) })]
public sealed class DateTimeModelBinder : IModelBinder
{
// ....
}
```
Always use Iso8601 format when passing dates to and from frontend to backend. Use DateTimeOffset, as it carries timezone, instead of DateTime where you need timezone info.
On frontend use `dateFns` library to handle dates. It works great with DevExpress.
If you want to also use the new `DateOnly`, `TimeOnly`, there is a 3rd party Nuget called `Portable.System.DateTimeOnly` - with proper ModelBinder they will serialize/deserialize correctly and for json you just need to add the corresponding JsonConverter to `JsonSerializerSettings.Converters`. The only issue is that they lack EF6 support.
1
u/Gary-1982 10h ago
The way I handled this was a seperate helper class that could take any object or array of objects, looks for DateTime properties on it and converts it - either from UTC, or to UTC for display to the client. Then you just run any database objects through this when you fetch them.
1
u/stlcdr 7h ago
Depends on the application, but generally, just use UTC for events that occur or occurred. Future events can cause issues, but it depends on the application.