DateTime.Now与系统时间 [英] DateTime.Now vs system time

查看:146
本文介绍了DateTime.Now与系统时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下这个小程序在运行:

Let's imagine that this little program runs:

while (true)
{
    Console.WriteLine($"{DateTime.UtcNow} -> {DateTime.Now} tz={TimeZone.CurrentTimeZone.StandardName} / {TimeZoneInfo.Local.StandardName}");
    await Task.Delay(TimeSpan.FromSeconds(1));
}

当我在程序运行时更改系统的时区时,应用程序看不到更改.时区和时间就像时区一样.

When I change the system's time zone when the program is running the app does not see the change. The timezone and the time is as if the timezone has not changed.

为了使应用程序显示新的时间和时区,我需要重新启动应用程序.

In order for the app to display the new time and time zone I need to restart the app.

如果我更改系统时间,则会立即获取时间更改.

If I change the system time the time change is picked up immediately.

如果您能帮助我解决三个问题,那就太好了

It would be great if you could help me with three questions:

  • 此文件记录在任何地方吗?
  • 为什么在运行应用程序时未获取时区更改?
  • 我可以做些什么,以便该应用在运行时获取时区更改吗?

以下是一些截图,显示了.NET应用程序使用的时间与操作系统不同:

Here's a little screenshot to show the .NET app using time different than the operating system:

顺便说一句.在Raspberry Pi上的Windows IOT上,我的实验表明,如果我重新启动该应用程序,它将显示新时区,但显示旧"时间.重新启动系统后,将获取新的时间.

BTW. On Windows IOT on Raspberry Pi, my experiment shows that if I restart the app it will show the new timezone, but the 'old' time. The new time will be picked up after restarting the the system.

推荐答案

您可以检查以下msdn

You can check the following msdn link. It clearly states the following :

给呼叫者的注释:当前时区数据在CurrentTimeZone之后被缓存首先用于检索时区信息.如果系统是本地的时区随后更改,CurrentTimeZone属性不更改反映这一变化.如果您需要在您的应用程序正在运行,请使用TimeZoneInfo类并调用其TimeZoneInfo.ClearCachedData方法.

Notes to Callers: Local time zone data is cached after CurrentTimeZone is first used to retrieve time zone information. If the system's local time zone subsequently changes, the CurrentTimeZone property does not reflect this change. If you need to handle time zone changes while your application is running, use the TimeZoneInfo class and call its TimeZoneInfo.ClearCachedData method.

此文件记录在任何地方吗?是的,如上所述.

为什么在应用程序运行时未选择时区更改?因为时区信息已缓存.

why isn't the timezone change picked up while the application is running? Because the timezone information is cached.

我可以做些什么,以便该应用在运行时获取时区更改吗?是的,通过使用TimeZoneInfo类并调用其TimeZoneInfo.ClearCachedData方法.

can I do anything so that the app picks up timezone changes while it's running? Yes, by using the TimeZoneInfo class and calling its TimeZoneInfo.ClearCachedData method.

这篇关于DateTime.Now与系统时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆