C#, Programmers Latrinalia

[C#] How to read an API date field as UTC?

Dealing with dates in different time zones is a thing that requires some attention 😉. Today I want to show you a quick trick you should make when reading a date. And by that, I mean getting the date from an external source (ex. some IoT stuff or a REST API).

To avoid keeping you in suspense 😛 – yes, the trick is to treat a date like an UTC date 😉. Yeah, I know, mind blown 😉.

To achieve this, just call a DateTime.SpecifyKind on the field you read. Just like this:

var dateToBeSavedInDataBase = DateTime.SpecifyKind(dateReadFromApi, DateTimeKind.Utc);

And that’s it. You can safely save your variable to the database 😉.

Photo by Julien Delaunay on Unsplash

Share this: