2014-02-22 98 views
2

下面是一个简单的代码:哪里DateTime.ToLocalTime()获取偏移

System.DateTime dt = new DateTime(635267088000000000); 
Console.WriteLine(dt.ToLocalTime()); 

我已经改变了位置,格式和系统区域设置在Windows的“区域和语言设置”,但结果却事与愿违改变。

我已重新启动计算机。我正在使用Windows 7.

回答

3

系统Timzone设置位于“日期和时间”控制面板中,而不是“区域和语言”控制面板(并且令人困惑的是,这也是键盘语言设置的位置,而不是键盘控制面板)。

+1

谢谢。它帮助到我 ! – demas

2

奇怪...您提供的代码无法识别本地信息,因为您没有指定本地类型。为了让在转换到本地或世界时的优势,你必须指定一种DateTime对象是这样的:

DateTime dtUtc = new DateTime(DateTime.UtcNow.Ticks, DateTimeKind.Utc); 
DateTime dtLocal = dtUtc.ToLocalTime(); 
Console.WriteLine("{0} - {1}", dtUtc, dtLocal); 

这将输出类似这样:

22/2/2014 10:25:59 - 22/2/2014 14:25:59 

请注意,如果您使用DateTime.NowDateTime.UtcNow他们已经分别有DateTimeKind.LocalDateTimeKind.Utc

DateTime dt = DateTime.Now; 
Console.WriteLine(dt.Kind); 
dt = DateTime.UtcNow; 
Console.WriteLine(dt.Kind); 
dt = new DateTime(635267088000000000); 
Console.WriteLine(dt.Kind); 

输出是:

Local 
Utc 
Unspecified 

探索这个例子。

DateTime dt = new DateTime(635267088000000000); // same as DateTimeKind.Unspecified 
DateTime dtUtc = dt.ToUniversalTime(); 
DateTime dtLocal = dt.ToLocalTime(); 
Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal); 

dt = new DateTime(635267088000000000, DateTimeKind.Local); 
dtUtc = dt.ToUniversalTime(); 
dtLocal = dt.ToLocalTime(); 
Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal); 

dt = new DateTime(635267088000000000, DateTimeKind.Utc); 
dtUtc = dt.ToUniversalTime(); 
dtLocal = dt.ToLocalTime(); 
Console.WriteLine("{0} - {1} - {2}", dt, dtUtc, dtLocal); 
+0

谢谢。我会检查代码。 – demas

+0

我不知道为什么,但你的例子给我“22.02.2014 11:55:47 - 22.02.2014 17:55:47” – demas

+0

如果我使用DateTimeKind.Local作为第二个参数,那么dtUtc和dtLocal将会是一样。看起来像DateTimeKind.Utc是第二个参数的默认值。 – demas