C# 22H2之后的windows版本使用SetDynamicTimeZoneInformation设置时区失败处理

本文介绍了如何在不同版本的Windows系统中使用SetDynamicTimeZoneInformation和PowerShellAPI来设置本地时区,特别关注了对旧系统(如WindowsXP)的兼容处理。

使用SetDynamicTimeZoneInformation设置时区返回false,设置失败。

使用PowerShell设置Set-TimeZone成功。

/// <summary>
/// 设置本地时区
/// 参数取值"China Standard Time",即可设置为中国时区
/// </summary>
/// <param name="timeZoneId"></param>
/// <returns></returns>
public static bool SetLocalTimeZone(string timeZoneId)
{
    var dynamicTimeZoneInformation = ConvertDynamicTimeZoneInformation(timeZoneId);
    bool success;
    // 检测当前系统是否为旧系统
    if (IsOldOsVersion())
    {
        var tzi = ConvertTimeZoneInformation(dynamicTimeZoneInformation);
        success = SetTimeZoneInformation(ref tzi);
    }
    else
    {
        success = SetDynamicTimeZoneInformation(ref dynamicTimeZoneInformation);
    }
    if (success)
    {
        TimeZoneInfo.ClearCachedData(); // 清除缓存
    }
    else
    {
        success = SetTimeZoneByPowerShe
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值