【问题标题】:Not Sure How To Convert to DateTimeOffset Correctly不确定如何正确转换为 DateTimeOffset
【发布时间】:2013-06-18 15:02:30
【问题描述】:

我们有一个包含 DateTime2(7) 列的表,我们试图从该列中获取值并将它们插入到另一个表中,该表的相应列数据类型为 DateTimeOffset。源日期如下所示:

2013-02-28 00:15:49.8270000
2013-03-11 00:26:38.1270000

我们希望它们转换为如下所示(假设东部标准时间 - 时间在 3 月 10 日向前移动一小时。)

2013-02-28 00:15:49.8270000 -05:00
2013-03-11 00:26:38.1270000 -04:00

我不确定如何告诉 SQL Server 获取源日期,并根据该日期和时间,使用 EST 时区将其转换为在该日期和时间生效的正确 DateTimeOffset。

我知道 ToDateTimeOffset 函数,但是,如果我理解正确,我必须为该函数提供一个偏移值。我希望 SQL Server 根据我提供的时区(例如 EST)来解决这个问题。

【问题讨论】:

  • 我认为没有任何内置功能。为此,您可能不得不求助于 SQLCLR。
  • @RichardDeeming - 是的,我害怕这个。

标签: sql-server-2008 tsql


【解决方案1】:

使用 SQLCLR 应该相当简单。假设时区始终是 EST,这样的事情应该可以工作:

using System;
using Microsoft.SqlServer.Server;

namespace SqlUtilities
{
   public static class Dates
   {
      private static readonly TimeZoneInfo EST = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

      [SqlFunction(
         Name = "ToDateTimeOffset",
         DataAccess = DataAccessKind.None,
         IsDeterministic = true,
         IsPrecise = true
      )]
      public static DateTimeOffset? ToDateTimeOffset(DateTime? value)
      {
         if (value == null) return null;

         var source = value.Value;
         var offset = EST.GetUtcOffset(source);
         return new DateTimeOffset(source, offset);
      }
   }
}

【讨论】:

    猜你喜欢
    • 2016-03-11
    • 2012-03-18
    • 1970-01-01
    • 2011-12-13
    • 2013-07-25
    • 2021-10-21
    • 2020-08-28
    • 2012-04-30
    • 1970-01-01
    相关资源
    最近更新 更多