I have DateTimeOffset:
DateTimeOffset myDTO = DateTimeOffset.ParseExact( "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture); Console.WriteLine(myDTO);
Result => "1/15/2015 17:37:00 -05:00"
How convert to DateTime and add this offset "-0500" in the resulted DateTime
Desired result => "1/15/2015 22:37:00"
You can also use the DateTimeOffset. LocalDateTime property to convert a DateTimeOffset value to a local DateTime value. The Kind property of the returned DateTime value is Local.
In performing the conversion to local time, the method first converts the current DateTimeOffset object's date and time to Coordinated Universal Time (UTC) by subtracting the offset from the time. It then converts the UTC date and time to local time by adding the local time zone offset.
The DateTimeOffset structure represents a date and time value, together with an offset that indicates how much that value differs from UTC. Thus, the value always unambiguously identifies a single point in time.
DateTimeOffset is both a . NET type and a SQL Server type (other databases have equivalents, too). The main difference between it and the simpler DateTime type we all know and love is that it includes a time zone offset from UTC.
Use DateTimeOffset.UtcDateTime
:
DateTime utc = myDTO.UtcDateTime; // 01/15/2015 22:37:00
You do not have to add the offset to the time when using UTC time. According to your example, you are referring to the UTC time. So this would mean that you can use DateTimeOffset.UtcDateTime
like I demonstrated here:
DateTimeOffset myDTO = DateTimeOffset.ParseExact( "2015/01/15 17:37:00 -0500", "yyyy/MM/dd HH:mm:ss zzz", CultureInfo.InvariantCulture); Console.WriteLine(myDTO); //Will print 1/15/2015 17:37:00 -5:00 //Expected result would need to be 1/15/2015 22:37:00 (Which is UTC time) DateTime utc = myDTO.UtcDateTime; //Yields another DateTime without the offset. Console.WriteLine(utc); //Will print 1/15/2015 22:37:00 like asked
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With