测试现在是否在跨午夜的两个时间之间

问题描述 投票:0回答:3

我尝试过搜索这个,但我很茫然……我可以找到其他语言的答案,但不能找到 PowerShell 的答案。

基本上,我想测试现在的时间是否在 21:15 到 5:45 之间。

我很确定我需要使用 New-TimeSpan - 但是,对于我的一生,我就是无法解决。

我会分享我的测试代码,但我认为我离答案太远了,它不会有任何帮助。

有人可以帮助我吗?

powershell timespan
3个回答
2
投票

使用

Get-Date
创建
DateTime
对象,将这些阈值描述为今天日期的时间点,然后测试现在的时间是在最早的时间之前还是在最晚的时间之后:

$now = Get-Date
$morning = Get-Date -Date $now -Hour 5 -Minute 45
$evening = Get-Date -Date $now -Hour 21 -Minute 15

$isWithinRange = $now -le $morning -or $now -ge $evening

2
投票

如果这纯粹是关于一天中的时间并且您不需要任何日期计算,您可以执行以下操作,因为对于填充数字字符串词法排序等于按时间顺序排序:

# Get the current point in time's time of day in 24-hour ('HH') format.
# Same as: [datetime]::Now.ToString('HH\:mm')
$timeNow = Get-Date -Format 'HH\:mm'

$timeNow -ge '21:15' -or $timeNow -le '05:45'

正如 xjcl 所指出的,您也可以将这种词法比较技术应用于完整时间戳;例如

$now = Get-Date
# Create a text-sortable representation of the date down to the minute.
$sortableNowString = Get-Date -Format 'yyyy-MM-dd HH\:mm'
# Create a reference timestamp in the same format.
$sortableRefString = (Get-Date -Format 'yyyy-MM-dd') + ' 13:00' # fixed time of day
# Compare: will only be $true after 1 PM
$sortableNowString -gt $sortableRefString 

与一天中不同时间的字符串格式

HH\:mm
一样,这取决于选择一种日期格式,其 lexical 排序相当于 chronological 排序。

但是,您不能以这种方式执行实际日期/时间计算,例如确定两个日期之间的时间跨度,或从日期中减去时间跨度。此类操作需要直接使用

[datetime]
(或
[datetimeoffset]
)和
[timespan]
实例;例如:

$now = Get-Date

# Same as: $now.TimeOfDay, i.e. returns the time of day as a [timespan]
$now - $now.Date 

# Same as: $now.Date, i.e. returns the very start of the calendar
#          day as a [datetime]
$now - $now.TimeOfDay

1
投票

如果您需要检查您是否在 23:00-04:00 范围内(跨越午夜),您可以:

$now=(Get-Date).TimeofDay
if ($now.TotalHours -ge 23 -or $now.TotalHours -lt 04)
{"In Range"}
else
{"Out of range"}
© www.soinside.com 2019 - 2024. All rights reserved.