在ASP上使用nodetime进行日期时间转换.Net MVC 3 Razor网站.如何



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

我的第一个问题是更相关的MVC结构,因为我是完全新的这(我是一个WebForms开发人员)-我应该把这个转换代码/类/助手?模型?视图模型?

第二个问题是转换本身-我已经使用了nodeatime测试项目,但无法找到进行此转换的适当方法。

任何帮助都非常感谢。

提前感谢。

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

// 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建议的代码片段

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

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

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

使用c#将DateTime从UTC转换为用户提供的时区

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

如何在ASP.NET中使用时区?

最新更新