喬恩斯基特可能需要糾正我,因爲我假設這是正確的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個可能日期。這裏的代碼只是獲得第一個或最早的日期/時間。
編輯:由喬恩斯基特
我會使用'londonTimeZone.AtLeniently'而不是地圖,但是否則這是正確的。值得注意的是'en-GB'(etc)不是正常的時區標識符。 – 2013-04-23 21:45:06
此外,它可能是值得更改'usersLocalDateTime'到'usersZonedDateTime',因爲它*是一個'ZonedDateTime'。 – 2013-04-24 08:05:18
@JonSkeet關於語言環境的好處。我應該以更好的方式提出我的問題。我將根據用戶的日期/時間設置(時區)進行此轉換 - 使用一個JavaScript插件,它將返回時區ID。保存在用戶個人資料中的語言環境將僅用於格式化結果。 – melancia 2013-04-24 08:47:50