Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now vs DateTime.UtcNow on Azure server hosting my site and db

I've been struggling with utc and local time for a while. I have an app that creates events (classes) and when the host creates an event (class), they set the event date and time. So, on the server side I save both the local date time for the event and the UTC date time for the event.

But now is where I keep confusing myself.

Example: If a user visits the hosts page to see all the hosts events (classes), how would I look up the host's events if I'm using a date time in the query and the user visiting the page is a different time zone from the host.

Currently I'm doing something like this:

var events = host.Events.Where(j => j.EventDateTime >= DateTime.Now
            && j.EventStatus == EventStatus.Active).ToList()

But now I'm frustrated over the DateTime.Now, because it's the date time of the Azure server and this query compares the local event date time to a UTC date time.

So my question is,
Should I try to figure out what the UTC date time is and pass that in before adding the offset to the DateTime.Now?

Or should I run the query using the UTC date times? Which would be something like this:

var events = host.Events.Where(j => j.UtcEventDateTime >= DateTime.UtcNow
            && j.EventStatus == EventStatus.Active).ToList()
like image 555
user1186050 Avatar asked Oct 26 '25 13:10

user1186050


1 Answers

Note that the DateTime.Now on the server means the server now datetime not the user Now, which might get you confused especially on the cloud when the application is distributed on multiple services, or when you change the location of your service.

It is always recommended to save dates in UTC format and you can add to this the offset based on each user zone for display, this will make sure that your date data are consistent and easy to compare and filter.

Many people had same questions like yours such as this good one: DateTime.Now vs. DateTime.UtcNow

Also you might find Datetimeoffset a different way to save your date, just make sure you understand it very well before adding it in action: DateTime vs DateTimeOffset

like image 65
Amr Elgarhy Avatar answered Oct 28 '25 02:10

Amr Elgarhy