powershelltimespan

Testing if now if between two times that span midnight


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?


Solution

  • 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