当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 使用 PowerShell 转换为当地时间

作者:精品下载站 日期:2024-12-14 08:00:41 浏览:12 分类:玩电脑

使用 PowerShell 转换为当地时间


正如你们中的一些人所知,我会在每个月的第一个星期五使用 #PSTweetChat 标签举办每月一次的在线 Twitter 聊天(尽管 2021 年 1 月的聊天将于 1 月 8 日进行。)我们在 1 点聚在一起讨论 PowerShell 的所有问题:东部时间下午 00 点。世界其他地区面临的挑战是确保他们知道自己的时间是什么时候。我也曾处于这件事的另一端。我需要参加中欧标准时间上午 10:00 的活动。那什么时候适合我呢?我每天都在 PowerShell 中度过,所以应该有一个简单的方法来回答这个问题。

日期时间恶作剧

当然有。 [DateTime] 类有一个名为 ToLocalTime() 的方法,它将 UTC 时间转换为本地时间。为了将我的 CET 上午 10:00 事件转换为本地时间,我需要转换该时间。转换为 UTC,然后转换为本地时间。

第一部分(是的,可以通过多种方式完成)是创建欧洲中部时间上午 10:00 的日期时间对象。我不能只运行 Get-Date,因为任何结果都将与我的时区相关。嗯,其实我可以。

 $datetime = Get-Date "12/30/2020 10:00AM"

我需要做的是调整这个值以匹配 CET 时区。为此,我需要知道时区。没问题。

$tzone = Get-TimeZone -Id "Central European Standard Time"

我假设您会查看此命令的帮助和示例。此结果包括反映 UTC 偏移时间跨度的属性。换句话说,距离 UTC 有多远。对于 CET,该时间为 1:00:00。我可以使用 AddHours() 方法来调整日期时间值。

$remoteTime = $DateTime.AddHours( - ($tzone.BaseUtcOffset.totalhours))

这是 UTC 值,我现在可以将其转换为本地时间。

$remoteTime.ToLocalTime()

[玩转系统] 使用 PowerShell 转换为当地时间

我在东部时间,所以我的 UTC 偏移量是 -5 小时。 CET 比这个时间还要多一个小时,总共 7 个小时,所以 10:00AM CET 对我来说实际上是 4:00AM。我想我可以放弃这次会议。

转换为本地时间

现在我已经解决了核心机制,我将把它包装在 PowerShell 函数中。

Function ConvertTo-LocalTime {
    <#
    .Synopsis
    Convert a remote time to local time
    .Description
    You can use this command to convert datetime from another timezone to your local time. You should be able to enter the remote time using your local time and date format.
    .Parameter Time
    Specify the date and time from the other time zone.
    .Parameter TimeZone
    Select the corresponding time zone.
    .Example
    PS C:\> ConvertTo-LocalTime "2/2/2021 2:00PM" -TimeZone 'Central Europe Standard Time'

    Tuesday, February 2, 2021 8:00:00 AM

    Convert a Central Europe time to local time, which in this example is Eastern Standard Time.
    .Example
    PS C:\> ConvertTo-LocalTime "7/2/2021 2:00PM" -TimeZone 'Central Europe Standard Time' -Verbose
    VERBOSE: Converting Friday, July 2, 2021 2:00 PM [Central Europe Standard Time 01:00:00 UTC] to local time.
    Friday, July 2, 2021 9:00:00 AM

    The calculation should take day light savings time into account. Verbose output indicates the time zone and its UTC offset.

    .Notes
    Learn more about PowerShell: https://jdhitsolutions.com/blog/essential-powershell-resources/
    .Inputs
    None
    .Link
    Get-Date
    .Link
    Get-TimeZone
    #>
    [cmdletbinding()]
    [alias("ctlt")]
    [Outputtype([System.Datetime])]
    Param(
        [Parameter(Position = 0, Mandatory, HelpMessage = "Specify the date and time from the other time zone. ")]
        [ValidateNotNullorEmpty()]
        [alias("dt")]
        [string]$Time,
        [Parameter(Position = 1, Mandatory, HelpMessage = "Select the corresponding time zone.")]
        [alias("tz")]
        [string]$TimeZone
    )
    #parsing date from a string to accommodate cultural variations
    $ParsedDateTime = Get-Date $time
    $tzone = Get-TimeZone -Id $Timezone
    $datetime = "{0:f}" -f $parsedDateTime

    Write-Verbose "Converting $datetime [$($tzone.id) $($tzone.BaseUTCOffSet) UTC] to local time."

    $ParsedDateTime.AddHours(-($tzone.BaseUtcOffset.totalhours)).ToLocalTime()
}

该函数要求您指定日期时间及其关联的时区。如果我能够进行测试,您应该能够使用本地日期时间格式指定日期。这就是为什么 Time 参数是一个字符串,而我调用 Get-Date。我需要确保解析的值对于您的文化有效。其余代码只是我刚才演示的更紧凑的版本。

[玩转系统] 使用 PowerShell 转换为当地时间

时区补全器

为了使其更易于使用,我想预先填充可能的时区值。换句话说,添加自动完成功能。在与函数相同的文件中,我有这段 PowerShell 代码来设置参数完成程序。

Register-ArgumentCompleter -CommandName ConvertTo-LocalTime -ParameterName TimeZone -ScriptBlock {
    param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter)

    #PowerShell code to populate $wordtoComplete
    (Get-TimeZone -ListAvailable | Sort-Object -Property ID).where({$_.id -match "$wordToComplete"}) |
        ForEach-Object {
            # completion text,listitem text,result type,Tooltip
            [System.Management.Automation.CompletionResult]::new("'$($_.id)'", "'$($_.id)'", 'ParameterValue', $_.BaseUtcOffset)
        }
}

脚本块中的代码被执行并提供完成值。您需要运行一个将生成结果的命令,并且每个结果都作为 CompletionResult 对象添加。我将 New() 方法的参数值显示为注释。

您还可以选择使用 $WordToComplete 参数作为通配符类型。在我的代码中,完整的参数是获取时区 ID,其中名称与我输入的任何内容相匹配。这意味着我可以开始输入:

ConvertTo-LocalTime -Time "12/30/20 10:00AM" -TimeZone europe

然后按 Ctrl+Space 调用 PSReadline,它会显示可能的值。

[玩转系统] 使用 PowerShell 转换为当地时间

您看到的 01:00:00 是 ToolTip 值,即 BaseUTCOffset。这在 PowerShell ISE 中看起来更好一些。

[玩转系统] 使用 PowerShell 转换为当地时间

顺便说一句,如果您输入:

ConvertTo-LocalTime -Time "12/30/20 10:00AM" -TimeZone 

然后按 Ctrl+Space,PowerShell 会提示您显示所有 140 个可能的值。我会让你自己尝试一下。

现在我有一个方便的 PowerShell 工具,它可以一目了然地告诉我是否需要早起或熬夜。

[玩转系统] 使用 PowerShell 转换为当地时间

我希望您能尝试一下这段代码,并让我知道您的想法。我特别想知道它对于那些非北美文化的用户来说是如何工作的。根据我有限的测试,我认为您可以使用当地文化输入日期时间,一切都应该按预期进行。但我很想确认。

学习并享受。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯