【问题标题】:DateTime conversions using NodaTime on ASP.Net MVC 3 Razor website. How to?在 ASP.Net MVC 3 Razor 网站上使用 NodaTime 进行日期时间转换。如何?
【发布时间】:2013-04-16 09:51:17
【问题描述】:

我将日期/时间存储在伦敦时区(不是 UTC)的数据库中。 我需要的是检索此日期/时间,将其转换为 UTC 并考虑用户的时区(他们在注册到网站时定义 - 即:en-GB、en-US 等)显示。

我的第一个问题与 MVC 结构更相关,因为我对此完全陌生(我是一名 WebForms 开发人员) - 我应该把这个转换代码/类/帮助器放在哪里?模型?视图模型?

第二个问题是转换本身 - 我玩过 NodaTime 测试项目,但找不到进行此转换的合适方法。

非常感谢任何帮助。

提前谢谢你。

【问题讨论】:

    标签: asp.net-mvc-3 datetime razor nodatime


    【解决方案1】:

    你可以像这样写一些扩展方法:

    public static DateTime ConvertToUtc(this DateTime d)
    {
        //do conversin and return it
    }
    

    只要您在页面顶部包含 ConvertToUtc 的命名空间,您就可以像 @Model.MyDate.ConvertToUtc() 一样从您希望的任何视图中调用它。 并进行转换,请参阅此页面

    Convert DateTime from UTC to a user provided time zone with C#

    http://www.dotnetcurry.com/ShowArticle.aspx?ID=593

    How to work with time zones in ASP.NET?

    【讨论】:

    • 非常感谢您的回答,但我目前正在这个项目上使用 NodaTime。
    【解决方案2】:

    Jon Skeet 可能需要纠正我,因为我假设这在 中是正确的:

    // Timezone data provider (inject with DI)
    IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;
    
    // London Timezone (can keep this as a singleton, since it'll be used often)
    var londonTimeZone = timeZoneProvider["Europe/London"];
    
    // Get your date/time from the database and map it as being local to London timezone
    var yourDateFromDb = new DateTime(2013, 01, 23, 21, 00, 00); // This is what you'll get back from your database (although you may get back a DateTimeOffset)
    ZoneLocalMapping zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(yourDateFromDb)); <-- This is your date time with the correct offset (taking into account DST etc.)
    
    // Map the London zoned date/time to the users local date/time
    var usersTimezoneId = "Europe/Paris"; // <-- Store this value in users profile/db
    var usersTimezone = timeZoneProvider[usersTimezoneId];
    var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);
    
    Assert.That(usersZonedDateTime.Hour == 22);
    

    您可能应该知道,在时区转换(秋季时钟更改)期间,您可能会获得 zonedDbDateTime 的 2 个可能日期。这里的代码只是获取第一个或最早的日期/时间。

    编辑:使用 Jon Skeet 建议的更改更新了代码 sn-p

    【讨论】:

    • 我会使用londonTimeZone.AtLeniently 而不是地图,否则就对了。可能值得注意的是,en-GB(等)不是正常的时区标识符。
    • 另外,可能值得将usersLocalDateTime 更改为usersZonedDateTime,因为它 ZonedDateTime
    • @JonSkeet 关于语言环境的好点。我应该以更好的方式提出我的问题。我将根据用户的日期/时间设置(时区)进行此转换 - 使用将返回时区 ID 的 javascript 插件。保存在用户配置文件中的区域设置仅用于格式化结果。
    • 感谢两位的回答。现在就试试。
    • @MelanciaUK: ZonedDateTime.ToDateTimeUtcZonedDateTime.ToDateTimeUnspecified 取决于您想要哪种类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 2013-03-29
    • 2020-01-18
    相关资源
    最近更新 更多