Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 644
Dan Avatar asked Oct 10 '14 09:10

Dan


1 Answers

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.

like image 148
Jon Skeet Avatar answered Oct 04 '22 22:10

Jon Skeet