【发布时间】:2013-02-07 10:58:06
【问题描述】:
我不能使用DateTime.Now,因为服务器不一定位于加州
【问题讨论】:
我不能使用DateTime.Now,因为服务器不一定位于加州
【问题讨论】:
两种选择:
1) 使用TimeZoneInfo 和DateTime:
using System;
class Test
{
static void Main()
{
// Don't be fooled - this really is the Pacific time zone,
// not just standard time...
var zone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var utcNow = DateTime.UtcNow;
var pacificNow = TimeZoneInfo.ConvertTimeFromUtc(utcNow, zone);
Console.WriteLine(pacificNow);
}
}
2) 使用我的Noda Time 项目:)
using System;
using NodaTime;
class Test
{
static void Main()
{
// TZDB ID for Pacific time
DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/Los_Angeles"];
// SystemClock implements IClock; you'd normally inject it
// for testability
Instant now = SystemClock.Instance.Now;
ZonedDateTime pacificNow = now.InZone(zone);
Console.WriteLine(pacificNow);
}
}
显然我有偏见,但我更喜欢使用 Noda Time,主要有以下三个原因:
DateTime试图表示三种不同的值,没有只表示“日期”或“一天中的时间”的概念
【讨论】: