为什么DateTime.ToLocalTime()不考虑夏令时?

编程入门 行业动态 更新时间:2024-10-10 19:16:27
本文介绍了为什么DateTime.ToLocalTime()不考虑夏令时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个用 DateTime.UtcNow.ToString( s)。我想显示一些面向用户的内容,例如 10:00 AM。我现在在(英格兰)的地方,时钟已经过去了,下面的方法要花一个小时了:

var timenowstring = DateTime.UtcNow.ToString( s); var dateutc = DateTime.Parse(timenowstring).ToShortTimeString(); var datelocal = DateTime.Parse(timenowstring).ToLocalTime()。ToShortTimeString(); Console.WriteLine( UTC时间字符串: + dateutc); Console.WriteLine(本地时间字符串: + datelocal);

当实际上是10:02 AM时,都打印 9:02 AM。

下面是在

库,例如:

DateTimeZone tz = DateTimeZoneProviders.Tzdb [欧洲/伦敦]; DateTime englandDateTime = Instant.FromDateTimeUtc(utcDateTime) .InZone(tz) .ToDateTimeUnspecified();

I have a a UTC time string (that I get from a database, so I can't change the format) that is created with DateTime.UtcNow.ToString("s"). I would like to display something user-facing like "10:00 AM". Where I am (in England), the clocks have recently gone forward and the following method is an hour out:

var timenowstring = DateTime.UtcNow.ToString("s"); var dateutc = DateTime.Parse(timenowstring).ToShortTimeString(); var datelocal = DateTime.Parse(timenowstring).ToLocalTime().ToShortTimeString(); Console.WriteLine("Utc time string: " + dateutc); Console.WriteLine("Local time string: " + datelocal);

Both print "9:02 AM" when actually it's 10:02 AM.

Here's a screenshot of it repro-ing on csharppad/ :

bigger image

CSharpPad gist

What am I doing wrong and what's the easiest way to get a DateTime object which will return the right time when I call .ToShortTimeString()?

NB the docs on ToLocalTime() say:

The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

解决方案

You said:

I have a a UTC time string (that I get from a database, so I can't change the format) that is created with DateTime.UtcNow.ToString("s").

Right off the bat, you have a problem. Dates in a database are (usually) not stored as strings. They're stored in fields with a specific data type. In SQL Server (for example) you may be using a datetime or datetime2 field. These are not strings. When you retrieve them into your .NET code, they are converted directly to a DateTime type. If you are treating it as a string, you are doing it wrong.

For example, your data access code might be doing something like this:

DateTime dt = Convert.ToDateTime(dataReader["myDateTimeField"].ToString());

That is very common, and completely wrong. You should instead be doing this:

DateTime dt = (DateTime) dataReader["myDateTimeField"];

Or if the field is nullable:

DateTime? dt = dataReader["myDateTimeField"] as DateTime;

Once you load the value properly instead of parsing it as a string, the rest will work out fine. The DateTime value will have DateTimeKind.Unspecified for its Kind property, and when you call ToLocalTime on it, it will assume that you wanted to treat the unspecified value as UTC. (See the chart on MSDN.)

Regarding the code you posted, while it's a bit messy (going through strings unnecessarily), it would actually work just fine - assuming you ran it in your time zone. In the ToLocalTime method, "local" means the local time zone setting of the machine wherever the code happens to be running. For csharppad, the time zone happens to be UTC. It has no way of knowing you want to use England's time zone rules.

If you intend to run your code on a server, then you shouldn't be using ToLocalTime at all - as the time zone of the server is likely to be irrelevant. Instead, you could use TimeZoneInfo to convert the time:

// this uses the time zone for England TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time"); DateTime englandDatetime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tz);

Alternatively, you could use the open-source Noda Time library, like this:

DateTimeZone tz = DateTimeZoneProviders.Tzdb["Europe/London"]; DateTime englandDateTime = Instant.FromDateTimeUtc(utcDateTime) .InZone(tz) .ToDateTimeUnspecified();

更多推荐

为什么DateTime.ToLocalTime()不考虑夏令时?

本文发布于:2023-11-23 20:15:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622753.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:夏令时   DateTime   ToLocalTime

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!