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

3

19

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?

Excruciate answered 10/10, 2014 at 9:37 Comment(3)
Use the LocalDateTime. You should have a [look][1] [1]: #180440Lustrum
You may be interested in DateTime vs DateTimeOffset.Shizue
Also, you are looking at Quartz's 1.0 docs. Quartz 2.0 changed this method to return a DateTimeOffset?, as shown here.Shizue
Y
47

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.

Ybarra answered 10/10, 2014 at 9:41 Comment(1)
Why was this answer so hard to find? The M$ Docs on this are evil!!! https://learn.microsoft.com/en-us/dotnet/standard/datetime/converting-between-datetime-and-offsetLeaves
M
0

I bumped to this problem and none of these was real answer (by this question title). Solution examples for question title:

var myDateTimeOffset = (DateTimeOffset)DateTime.UtcNow;
var ans1 = myDateTimeOffset.DateTime.ToLocalTime();
var ans2 = myDateTimeOffset.DateTime.ToLocalTime().ToLocalTime(); // ans1==ans2

.NET5 C# 9.0

enter image description here

Moderate answered 1/4, 2021 at 18:33 Comment(0)
R
-2

This code is to convert utc to local

var local = utc.ToLocalTime();
Riflery answered 10/10, 2014 at 9:40 Comment(2)
That's just going to change the DateTime's kind, without changing its value at all. If the OP is simply displaying the value, then they wont see any changeYbarra
The OP is indeed simply displaying the valueExcruciate

© 2022 - 2025 — McMap. All rights reserved.