在ASP.Net MVC 3剃刀网站使用NodaTime日期时间转换。如何? [英] DateTime conversions using NodaTime on ASP.Net MVC 3 Razor website. How to?

查看:227
本文介绍了在ASP.Net MVC 3剃刀网站使用NodaTime日期时间转换。如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the Date/Time stored in the database on the London's time zone (not UTC). What I need is to retrieve this Date/Time, convert it to UTC and display considering the user's time zone (which they define when registering to the site - ie: en-GB, en-US, etc).

我的第一个问题是,更关系到MVC结构,我完全新本(是一个WebForms的开发者) - 我应该在哪里把这个转换code /班/帮手?模型?视图模型?

My first question is more related to the MVC structure, as I'm totally new to this (am a WebForms developer) - Where should I put this conversion code/class/helper? Model? ViewModel?

第二个问题是转换本身 - 我与NodaTime测试项目周围播放,但不能找到一种合适的方式来做到这一点的转换

The second question is the conversion itself - I've played around with the NodaTime test project but can't find a proper way to do this conversion.

任何帮助很多AP preciated。

Any help is much appreciated.

感谢您提前。

推荐答案

乔恩斯基特可能需要纠正我,因为我假设这是正确的 nodatime

Jon Skeet may need to correct me, as I'm assuming this is correct in 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可能的日期。在code这里只是获取第一个或最早的日期/时间。

You should probably be aware that during timezone transitions (autumn clock change), you may get 2 possible dates for the zonedDbDateTime. The code here just gets the first or earliest date/time.

编辑:更新code段与乔恩斯基特建议修改

Updated code snippet with changes suggested by Jon Skeet

这篇关于在ASP.Net MVC 3剃刀网站使用NodaTime日期时间转换。如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆