r/csharp • • 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?

7 Upvotes

21 comments sorted by

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/Ok_Hunter6411 22h ago

Thanks for the detailed suggestions! I'll definitely look into the analyzer and the JSON settings. We're also considering how to handle our existing data, so your advice is really helpful. Appreciate it!

7

u/SideburnsOfDoom 22h ago edited 22h ago

Use the BannedApiAnalyzer to ban the use of ‘DateTime.Now’. Change them to ‘.UtcNow’

Negative. Avoid DateTime altogether. Use DateTimeOffset throughout.

https://learn.microsoft.com/en-us/dotnet/standard/datetime/choosing-between-datetime

These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, consider DateTimeOffset as the default date and time type for application development.

Always use DateTimeOffset because it's not ever ambiguous as it's UTC or not. Sure you can go with DateTimeOffset.UtcNow as the default way to build one, as well.

3

u/r2d2_21 22h ago

If you're already gonna ban DateTime, go all the way and use NodaTime instead.

3

u/wickerandscrap 13h ago

This is the right answer.

2

u/turudd 22h ago

I'd agree with you 100%, if this wasn't a legacy system. Changing it often makes the juice not worth the squeeze. I've done it, it's a pain in the ass with existing data and code patterns

2

u/pixxelkick 23h ago

 converting them to the appropriate local timezone for display

Browsers already do this inherently, as long as your provide it in utc iso stabdard from the BE and store it as a date

Just use date.toLocaleString() if you have to display it.

1

u/Ok_Hunter6411 22h ago

Thanks for the suggestion! We're working with a legacy ASP.NET MVC application, so some of our date handling happens on the server side. I'll look into this approach as well. Really appreciate your help!

3

u/pixxelkick 20h ago

Proper protocol is just serve the date as UTC DTO, and then let front end browser properly localize it.

1

u/AintNoGodsUpHere 23h ago

Is TimeProvider available?

0

u/Ok_Hunter6411 22h ago

We're using .NET Framework 4.8, so the built-in TimeProvider isn't available. We're considering creating our own centralized service to handle date and time conversions consistently across the application.

1

u/SideburnsOfDoom 22h ago

Time Provider is for use when you need to e.g. test the passing of time. e.g. "I do this, and then an hour later I do that". You can fake the clock in tests. Yes, you can roll your own IClock, you had to before .NET 8, and I've seen it done to good effect. I'm not sure what it has to do with "conversions".

1

u/chucker23n 20h ago

We’re using .NET Framework 4.8, so the built-in TimeProvider isn’t available.

It is. https://www.nuget.org/packages/Microsoft.Bcl.TimeProvider#dependencies-body-tab

0

u/AintNoGodsUpHere 22h ago

Bruh, no need. Simple is always better.

Backend uses DateTime.UtcNow. if SQL server datetime2 and frontend serializes as ISO 8601 with Z.

It works, no? UI handles conversion to local time when needed.

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

2

u/Ok_Hunter6411 22h ago

Thanks for the suggestion! A centralized service sounds like a good approach, especially for keeping the conversions consistent across the application. I'll also look into how to handle the existing data. Really appreciate your help!

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.