Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateTimeOffset to DateTime and add offset to this DateTime

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"

like image 304
Alex Avatar asked Jan 15 '15 08:01

Alex


People also ask

How do you change date time offset of a given date?

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.

How do I convert DateTimeOffset to local time?

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.

What does offset mean in DateTime?

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.

Is DateTimeOffset UTC?

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.


2 Answers

Use DateTimeOffset.UtcDateTime:

DateTime utc = myDTO.UtcDateTime; // 01/15/2015 22:37:00 
like image 178
Tim Schmelter Avatar answered Sep 25 '22 01:09

Tim Schmelter


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 
like image 44
RvdV79 Avatar answered Sep 26 '22 01:09

RvdV79