gpt4 book ai didi

powershell - 从 ISO 8601 持续时间获取 DateTime 对象

转载 作者:行者123 更新时间:2023-12-02 22:49:41 25 4
gpt4 key购买 nike

在PowerShell中,有没有办法翻译duration as specified by ISO 8601到 DateTime 对象?例如,PT30M 是 30 分钟前,因此如果现在的时间是 2019-07-31 17:00:00,我想要的时间戳为 2019 -07-31 16:30:00

我已经尝试过显而易见的方法 -

"PT30M" | Get-Date

但这(不出所料地失败了)

Get-Date : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

我的下一个想法是编写一个函数来提取天、小时和分钟(例如,最多仅 30 天)。为此,以下函数起作用并根据传入的 $Duration 创建 $startTime

不过,感觉有点不对劲。首先,正则表达式仅非常具体地检查天、分钟和小时,而 $Duration 的其余部分可能完全是垃圾。其次,一旦考虑到秒、周、月之类的事情,那就很麻烦了。

是否有内置的方法可以做到这一点,或者坚持使用最佳选项下面的功能?

function Get-TimespanFromDuration
{
param(
[Parameter(Mandatory)]
[string]$Duration
)

$now = (Get-Date).ToUniversalTime()
$dataTimeAgo = @{ "Days" = 0; "Hours" = 0; "Minutes" = 0 }

### Work out how may days ago.
$daysAgo = $Duration -match "\D([1-9]|[1-2][0-9]|30)D"
if ($daysAgo)
{
[int]$dataTimeAgo["Days"] = $matches[0] -replace "\D+"
}

### Work out how may hours ago.
$hoursAgo = $Duration -match "\D([1-9]|1[0-9]|2[0-4])H"
if ($daysAgo)
{
[int]$dataTimeAgo["Hours"] = $matches[0] -replace "\D+"
}

### Work out how many minutes ago.
$minutesAgo = $Duration -match "\D([1-9]|[1-5][0-9]|60)M"
if ($minutesAgo)
{
[int]$dataTimeAgo["minutes"] = $dataTimeAgo["minutes"] + ($matches[0] -replace "\D+")
}

$startTime = $now.AddDays(-($dataTimeAgo["Days"])).AddHours(-($dataTimeAgo["hours"])).AddMinutes(-($dataTimeAgo["minutes"])).ToString("yyyy-MM-ddTHH:mm:ss.0Z")
$endTime = $now.ToString("yyyy-MM-ddTHH:mm:ss.0Z")

return ("{0}/{1}" -f $startTime, $endTime)
}

最佳答案

您可以在 PowerShell 中使用一个 .NET 类:[System.Xml.XmlConvert]::ToTimeSpan("PT30M")

关于powershell - 从 ISO 8601 持续时间获取 DateTime 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com