udaya726
udaya726

Reputation: 1020

Calculate datetime from datatimeoffset

I have a datetimeoffset value as 11/22/2016 05:20 AM with an offset of -06:00. I want to get the result as 11/21/2016 11:20 PM after reducing the offset from the time value. I tried

date.UtcDateTime

but it gives me the result as 11/22/206 11:20 PM . What is the way to get the preferred result from datetimeoffset value

Upvotes: 0

Views: 800

Answers (1)

Gerard Ashton
Gerard Ashton

Reputation: 638

The following example shows that when a DateTimeOffset is created, the year, month, day, hour, minute, etc. are interpreted as a local time in the time zone specified by the offset (in udaya726's case, -6 hours). The default output, "11/22/2016 05:20:00 -06:00", should be read as "November 22, 2016, 5:20 AM in the time zone 6 hours behind Greenwich."

using System;

public class StOv4
{
    public static void Main()
    {
        // Time in question: 11/22/2016 05:20 AM with an offset of -06:00
        TimeSpan questionOffset = new TimeSpan(-6, 0, 0);
        DateTimeOffset questionTime = new DateTimeOffset(2016, 11, 22, 5, 20, 0, 0,
            questionOffset);
        Console.WriteLine("Time with {0} offset: {1}", questionOffset, questionTime);
        // "u" format specifier indicates string is to represent UTC time.
        Console.WriteLine("UTC time: {0}", questionTime.ToString("u"));

    }
}

Console output:

Time with -06:00:00 offset: 11/22/2016 05:20:00 -06:00
UTC time: 2016-11-22 11:20:00Z

Upvotes: 1

Related Questions