【问题标题】:Date Time Struct to deal with different time zonesDate Time Struct 处理不同时区
【发布时间】:2017-03-17 03:27:18
【问题描述】:

我将结构名称命名为 DateTimeZone ,我将其设置为采用 UTC 时间,并让它采用本地时间。

    DateTimeZone time = DateTime.Now;//time will equal the UTC time
    DateTime localTime= time; // local time will equal the Local time

结构

  public struct DateTimeZone
{
    private DateTime dateTime;

 //   public  DateTimeZone Value { get; }

    public static implicit operator DateTimeZone(DateTime value)
    {
        return new DateTimeZone() { dateTime = value.ToUniversalTime() };
    }

    public static implicit operator DateTime(DateTimeZone value)
    {
        return value.dateTime.ToLocalTime();
    }
}

我的问题:有没有比结构更简单的方法来实现它? 当我保存在数据库中导致实体框架工作时,这个结构有异常, 所以我每次使用 struct 都需要进行映射,如何以简洁的方式进行映射?

【问题讨论】:

  • DateTime 是时区意识。老实说,不清楚你想做什么,但最好使用Nodatime,这是一个更好的 DateTime API。
  • 谢谢,我的时区有问题,所以我需要 datetime 将 utc 时间保存在数据库中,并在显示 UI 时获取本地时间,我修改了问题

标签: c# entity-framework datetime struct timezone


【解决方案1】:

也许你应该试试这个:

public struct DateTimeZone
{
    public DateTime DateTime;

    public static explicit operator DateTimeZone(DateTime dt)
    {
        return new DateTimeZone { DateTime = dt.ToUniversalTime() };
    }
}

var time = (DateTimeZone)DateTime.Now;
var localTime = time.DateTime; 

【讨论】:

    【解决方案2】:

    一些事情:

    • 请谨慎命名。名称如 DateTimeZone 的对象应包含 1) 仅时区信息,或 2) 日期、时间和时区。您的对象只是DateTime 的封装包装器,因此它们都不是。

    • 隐式操作可能是邪恶的 - 特别是如果它们改变了您正在使用的值的含义。我不建议将它们与日期/时间一起使用,除非您真的知道自己在做什么。该对象的任何用户很快就会对您实际使用的值感到困惑。

    • ToUniversalTimeToLocalTime 函数根据分配给您正在使用的 DateTime 对象的 .Kind 属性的 DateTimeKind 更改其行为。您似乎正在创建一个 API,其中 DateTime 始终是本地的,DateTimeZone 始终是 UTC,但 DateTimeKind 会妨碍这个想法。

    • 如 cmets 中所述,您可能会考虑使用 Noda Time,这是一个非常可靠且经过深思熟虑的 API。在 Noda Time 中,Instant 类型始终表示 UTC,LocalDateTime 类型始终表示无时区日期和时间。时区由DateTimeZone 表示(请参阅与您的名字的冲突),ZonedDateTime 类型结合了这些,这样您就可以同时拥有即时信息、本地时间信息和关联的时区。

    • 您提到了实体框架。不幸的是,EF 不能直接与您的自定义对象或 Noda Time 一起使用。它不具备进行简单类型转换的能力。这已被要求,但尚未实施。 You can follow the work item for it here。您可以使用的解决方法是“伙伴属性”@​​987654323@。他们不好玩,但他们工作。大部分。

    • 您可能会发现只使用DateTime 并在需要时手动调用ToUniversalTimeToLocalTime 等方法是合理的。如果您希望 EF 在从数据库加载时正确设置DateTimeKind,请参阅this answer

    • 请记住,ToUniversalTimeToLocalTime 都使用恰好运行代码的计算机的本地时区。这适用于桌面和移动应用程序,但很少用于 Web 应用程序,因为更改服务器的时区可能会严重影响数据。考虑改为通过内置的 TimeZoneInfo 类或 Noda Time 中的 DateTimeZone 类使用命名时区。

    为您补充阅读:

    【讨论】:

      猜你喜欢
      • 2017-05-17
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      相关资源
      最近更新 更多