r/csharp • u/Ok_Hunter6411 • 7d 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?
18
u/turudd 7d 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 7d 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.2
u/AintNoGodsUpHere 7d ago
Is TimeProvider available?
4
u/RichardD7 7d ago
Make sure you read Jon Skeet's 2019 blog post:
Storing UTC is not a silver bullet | Jon Skeet's coding blog
3
u/Uknight 7d 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
1
u/Mu5_ 7d 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 7d 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 7d 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/stlcdr 7d 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.
1
u/ApprehensiveDebt3097 17h ago
I would go for UTC based date times. Now calls I would advise to use Qowaiv.Clock.UtcNow().
https://github.com/Qowaiv/Qowaiv/blhttps://github.com/Qowaiv/Qowaiv/blob/main/docs/Clock.mdob/main/docs/Clock.md
0
u/Gary-1982 7d 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.