如何将DateTimeOffset转换回DateTime

时间:2016-11-29 09:39:27

标签: c# datetime timezone datetimeoffset

当我们创建搜索索引并将字段定义为DateTime时,类型为Edm.DateTimeOffset。值应该是这样的:yyyy-MM-ddTHH:mm:ss.fffZyyyy-MM-ddTHH:mm:ss.fff[+|-]HH:mm

现在我在DateTime类型的数据库中有一个文件,它被转换为Offset,如下所示:

 DateTime offset = //get from database the date

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

我的问题:如何将offsetConverted转换为原始的DateTime offset

1 个答案:

答案 0 :(得分:2)

使用DateTimeOffset类的DateTime属性将DateTimeOffset转换为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);
        }
    }
}

控制台输出:

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.