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

16 Upvotes

32 comments sorted by

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/Ok_Hunter6411 7d 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!

13

u/SideburnsOfDoom 7d ago edited 7d 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.

6

u/r2d2_21 7d ago

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

4

u/wickerandscrap 7d ago

This is the right answer.

2

u/turudd 7d 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

0

u/SagansCandle 2d ago

DateTimeOffset is 16 bytes versus 8 with DateTime. You're taking a significant runtime performance hit for design-time clarity. IMO static analysis is better design-time UTC enforcement.

Also consider DateOnly and TimeOnly, which are both 4-bytes each, where a full timestamp is not necessary.

0

u/SideburnsOfDoom 2d ago edited 2d ago

You're taking a significant runtime performance hit

I disagree that it is "significant" performance issue to use a slightly larger struct. That's a ridiculous point of view as a general statement about most apps. It is not "significant" when compared to GC, http request / response cycles, async database access etc.

If you have profiled your app and found this to be a significant issue in your case then go ahead, but ... have you really?

"design-time clarity" is an odd way to put that you can avoid runtime bugs due to time offset ambiguity.

I agree that DateOnly and TimeOnly are useful types, when the data matches the intent of those types. As I said here. e.g. TimeOnly is a better way to represent facts such as "Stores open at 08:30, local time on weekdays". There's no date or time zone in tht fact.

That does not diminish the fact that of the types that are in the .NET standard libraries, DateTimeOffset is recommended by Microsoft "as the default date and time type for application development". For good reasons.

2

u/kissqt 2d ago

I doubt it 99% of Devs if not more are impacted by this. I am working on a solution with a decent traffic (processing 400 files per sec, not request) and we are not even close to this kind of optimisation. Datetimeoffset is fine

2

u/SideburnsOfDoom 1d ago edited 1d ago

99% of Devs if not more are not impacted by this. we are not even close to this kind of optimisation. Datetimeoffset is fine

Exactly. Calling it "a significant runtime performance hit" as general advice is an opinion that signals "Tell me you don't understand optimisation - not even the Knuth quote - without saying 'I don't understand optimisation'".

0

u/SagansCandle 2d ago

It's a runtime cost for a design-time benefit. If we're seeking a design-time solution to UTC enforcement, static analysis can accomplish the same goal without the runtime cost.

0

u/SideburnsOfDoom 2d ago edited 2d ago

As I said, I don't agree that it's merely a "design-time benefit" or that it's a cost of any significance at all. Every line of code is a "run-time cost", that's not in itself an compelling argument against lines of code that give benefits. You are repeating your arguments. This is silly.

Microsoft's recommendation for DateTimeOffset over DateTime is what it is, that is not arguable.

0

u/SagansCandle 2d ago

If your system is strictly UTC, the point of failure is at the time the data is loaded.

DateTime.Now                 // Local time, Kind.Local
DateTime.UtcNow              // UTC, Kind.Utc

DateTimeOffset.Now           // Local time with explicit UTC offset
DateTimeOffset.UtcNow        // UTC with offset +00:00

Using DateTimeOffset doesn't solve your problem. Static analysis does. Same when you're initializing the value from an external source, such as a DB or REST API.

DateTimeOffset makes sense in application components that have legitimate cases where multiple time-zones must interact. In these cases, DateTimeOffset should be the natural choice, anyway.

My objection is to DateTimeOffset as the default - it's designed for dealing with different time zones. If your system's primarily UTC, it's a cost without a benefit.

As for being Microsoft's recommendation, I'm guessing you don't think they're always correct, unless you've installed OneDrive on your home PC and let them overtake your My Documents, right?

1

u/SideburnsOfDoom 2d ago edited 2d ago

As for being Microsoft's recommendation, I'm guessing you don't think they're always correct,...

This is doesn't go the way that you want: The "don't listen to MS" option in this argument is not "use DateTime", it is Use NodaTime.

I said what I said, and the phrase "of the types that are in the .NET standard libraries" is not in that sentence by accident.

0

u/SagansCandle 2d ago edited 2d ago

This is an insulting and pointless straw man.

It was an appropriate rebuttal to argument from authority.

I provided practical reasons for my position. Awaiting yours.

The "don't listen to MS" option in this argument is not "use DateTime", it is Use NodaTime.

So that was Microsoft's recommendation you just asserted?

1

u/SideburnsOfDoom 2d ago edited 2d ago

I provided practical reasons for my position. Awaiting yours.

I am sorry that you can't read and understand what has already been said. I have better things to do than repeat myself another time to someone who is invested in not understanding. Have a nice day, goodbye.

2

u/pixxelkick 7d 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 7d 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!

4

u/pixxelkick 7d ago

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

2

u/AintNoGodsUpHere 7d ago

Is TimeProvider available?

0

u/Ok_Hunter6411 7d 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 7d 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 7d 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

1

u/AintNoGodsUpHere 7d 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.

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

2

u/Ok_Hunter6411 7d 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 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.