user2818430
user2818430

Reputation: 6029

How to convert DateTimeOffset back to DateTime

When we create a search index and we define a field as DateTime the type is Edm.DateTimeOffset. And the value should be like this: yyyy-MM-ddTHH:mm:ss.fffZ or yyyy-MM-ddTHH:mm:ss.fff[+|-]HH:mm.

Now I have a file in my database of type DateTime that get's converted to Offset like this:

 DateTime offset = //get from database the date

 TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
 DateTimeOffset offsetConverted = new DateTimeOffset(offset, zone.GetUtcOffset(offset));

My question: how can I convert offsetConverted to my orginal DateTime offset?

Upvotes: 1

Views: 7029

Answers (1)

Gerard Ashton
Gerard Ashton

Reputation: 638

Use the DateTime property of the DateTimeOffset class to convert the DateTimeOffset to a DateTime.

using System;

namespace StackOverflowProblem1
{
    class Program
    {
        static void Main(string[] args)
        {
            // input comes from user in form yyyyddMMTHHmmss
            DateTime offset = new DateTime(2016, 10, 12, 12, 22, 0);
            TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById("FLE Standard Time");
            DateTimeOffset offsetConverted = new DateTimeOffset(offset, zone.GetUtcOffset(offset));
            DateTime roundTripOffset = offsetConverted.DateTime;
            Console.WriteLine("Input {0}, as DateTimeOffset {1},",
                  offset.ToString(),
                  offsetConverted.ToString());
            Console.WriteLine("after round trip {0}, Kind {1}.",
                 roundTripOffset,
                 roundTripOffset.Kind);
        }
    }
}

Console output:

Input 10/12/2016 12:22:00, as DateTimeOffset 10/12/2016 12:22:00 +03:00,
after round trip 10/12/2016 12:22:00, Kind Unspecified.

Upvotes: 2

Related Questions