Testing if now if between two times that span midnight

Viewed 328

I've tried searching for this, but I'm at a loss... I can find answers for other languages, but not for PowerShell.

Basically, I want to test if the time now is between 21:15 and 5:45.

I'm pretty sure I need to use New-TimeSpan - but, for the life of me, I just can't work it out.

I'd share my test code, but I think I'm so far away from the answer that it wouldn't be of any help.

Can anyone help me?

3 Answers

Use Get-Date to create DateTime objects describing those thresholds as points in time on todays date, then test if the time right now is before the early one or after the late one:

$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

If this is purely about the time of day and you don't need any date calculations, you can do the following, relying on the fact that for padded number strings lexical sorting equals numeric sorting:

# 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'

If you'd have to check if you are in the range 23:00-04:00, crossing the midnight, you could:

$now=(Get-Date).TimeofDay
if ($now.TotalHours -ge 23 -or $now.TotalHours -lt 04)
{"In Range"}
else
{"Out of range"}
Related