2013-04-23 72 views
1

我在倫敦時區(不是UTC)存儲數據庫中的日期/時間。 我需要的是找回此日期/時間,將其轉換爲UTC,並顯示考慮到用戶的時區(他們註冊到網站的時候定義 - 即:EN-GB,EN-US,等等)。在ASP.Net MVC 3 Razor網站上使用NodaTime進行DateTime轉換。如何?

我的第一個問題是,更關係到MVC結構,我完全新本(是一個WebForms的開發者) - 我應該在哪裏把這個轉換代碼/班/幫手?模型?視圖模型?

第二個問題是轉換本身 - 我與NodaTime測試項目周圍播放,但不能找到一個適當的方式做到這一點的轉換。

任何幫助,非常感謝。

預先感謝您。

回答

3

喬恩斯基特可能需要糾正我,因爲我假設這是正確的

// 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個可能日期。這裏的代碼只是獲得第一個或最早的日期/時間。

編輯:由喬恩斯基特

+1

我會使用'londonTimeZone.AtLeniently'而不是地圖,但是否則這是正確的。值得注意的是'en-GB'(etc)不是正常的時區標識符。 – 2013-04-23 21:45:06

+0

此外,它可能是值得更改'usersLocalDateTime'到'usersZonedDateTime',因爲它*是一個'ZonedDateTime'。 – 2013-04-24 08:05:18

+0

@JonSkeet關於語言環境的好處。我應該以更好的方式提出我的問題。我將根據用戶的日期/時間設置(時區)進行此轉換 - 使用一個JavaScript插件,它將返回時區ID。保存在用戶個人資料中的語言環境將僅用於格式化結果。 – melancia 2013-04-24 08:47:50

0

你可以寫一些擴展方法是這樣的:

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

,你將能夠調用它像@ Model.MyDate.ConvertToUtc()從你想,只要任何看法,你有命名空間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?

+0

建議修改更新的代碼段非常感謝您的回答,但我目前使用NodaTime在這個項目上。 – melancia 2013-04-23 09:04:32

相關問題