3

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()
Xander Luciano
  • 3,753
  • 7
  • 32
  • 53
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 2
    Please consider that UtcNow and Now are just different formats of the same time and both are user inputs. Do not trust the user always take the Utc time of your sever! – NjamNjam Aug 25 '18 at 23:45

1 Answers1

3

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

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301