How to convert a UTC DateTimeOffset to a DateTime that uses the systems timezone

Dan picture Dan · Oct 10, 2014 · Viewed 22.6k times · Source

Quartz.net offers a method to get the next time of the next trigger event: http://quartznet.sourceforge.net/apidoc/1.0/html/html/cc03bb79-c0c4-6d84-3d05-a17f59727c98.htm

The docs claim that this Trigger.GetNextFireTimeUtc() method return a DateTime? but it actually returns a DateTimeOffset?. I don't really get what DateTimeOffset is for or why this function return one instead of a regular DateTime. All I want is the next time the trigger is going to run but in my timezone.

I did this trigger.GetNextFireTimeUtc().Value.DateTime but it gave me a time 2 hours early, i.e. the UTC time. How can I get the correct time according to my computer?

Answer

Jon Skeet picture Jon Skeet · Oct 10, 2014

You can just use the DateTimeOffset.LocalDateTime property:

trigger.GetNextFireTimeUtc().Value.LocalDateTime

From the documentation:

If necessary, the LocalDateTime property converts the current DateTimeOffset object's date and time to the local system's date and time. The conversion is a two-step operation:

  • The property converts the current DateTimeOffset object's time to Coordinated Universal Time (UTC).
  • The property then converts UTC to local time.

You should really look into DateTimeOffset though - it's an important type to understand if you're using the BCL for date/time work.