DateTime.Now.ToLocalTime() 不刷新?
DateTime.Now.ToLocalTime() not refreshing?
请不要问我为什么,但我需要编写一个简单的程序,以系统配置的格式打印出当前系统日期和时间。
示例:
系统日期为 03.03.2018 ,单击按钮并以 dd.mm.yyyy 格式打印日期
将系统 Region/Clock 更改为 03/03/2018,单击 按钮并以 dd/mm/yyyy 格式打印出来。
我尝试的是编写一个方法,使用 DateTime class 并将 DateTime.Now 分配给 DateTime var。然后使用属性 "ToLocalTime()" 获取正确的格式。
只要我点击刷新按钮,就会调用此方法。
private String getSystemDate(){
DateTime date = DateTime.Now;
date = date.ToLocalTime();
return date.ToString(); ;
}
问题是,我分配给 getSystemDate() 的 return 值的标签不包含正确的格式。
只有重新启动应用程序后,日期才会以新格式显示。
有什么建议吗?
您需要清除语言环境缓存。当您的应用程序启动时,它会缓存当前的 Windows 语言环境。它不会自行刷新。
https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.clearcacheddata.aspx
(强调我的)
Information, such as the default culture and format patterns, is cached the first time it is requested. That information can change during the life of the AppDomain, for example, when the user modifies the regional and language options portion of Control Panel. However, the CultureInfo
class does not automatically detect changes in the system settings.
The ClearCachedData
method clears the cache of CultureInfo
objects created by GetCultureInfo
and refreshes the information in the CurrentCulture
, CurrentUICulture
, and CurrentRegion
properties, based on the current system settings.
The ClearCachedData method does not refresh the information in the Thread.CurrentCulture
property for existing threads. However, future threads will have any new CultureInfo
property values.
请不要问我为什么,但我需要编写一个简单的程序,以系统配置的格式打印出当前系统日期和时间。
示例: 系统日期为 03.03.2018 ,单击按钮并以 dd.mm.yyyy 格式打印日期 将系统 Region/Clock 更改为 03/03/2018,单击 按钮并以 dd/mm/yyyy 格式打印出来。 我尝试的是编写一个方法,使用 DateTime class 并将 DateTime.Now 分配给 DateTime var。然后使用属性 "ToLocalTime()" 获取正确的格式。 只要我点击刷新按钮,就会调用此方法。
private String getSystemDate(){
DateTime date = DateTime.Now;
date = date.ToLocalTime();
return date.ToString(); ;
}
问题是,我分配给 getSystemDate() 的 return 值的标签不包含正确的格式。 只有重新启动应用程序后,日期才会以新格式显示。
有什么建议吗?
您需要清除语言环境缓存。当您的应用程序启动时,它会缓存当前的 Windows 语言环境。它不会自行刷新。
https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.clearcacheddata.aspx
(强调我的)
Information, such as the default culture and format patterns, is cached the first time it is requested. That information can change during the life of the AppDomain, for example, when the user modifies the regional and language options portion of Control Panel. However, the
CultureInfo
class does not automatically detect changes in the system settings.The
ClearCachedData
method clears the cache ofCultureInfo
objects created byGetCultureInfo
and refreshes the information in theCurrentCulture
,CurrentUICulture
, andCurrentRegion
properties, based on the current system settings.The ClearCachedData method does not refresh the information in the
Thread.CurrentCulture
property for existing threads. However, future threads will have any newCultureInfo
property values.