# Check if current time is a specific time

• ### Question

• I need to check if the current time equals a specific time, for example:

If ((Get-Date) -eq [DateTime]'18:10:57') { do something }

But it does not work as I do the following step by step:

PS C:\> \$t = Get-Date
PS C:\> \$t
Tuesday, April 3, 2018 6:10:57 PM
PS C:\> [DateTime]'18:10:57'
Tuesday, April 3, 2018 6:10:57 PM
PS C:\> \$t -eq [DateTime]'18:10:57'
False
PS C:\>

Tuesday, April 3, 2018 10:27 PM

• It is not equal because it is not equal.  ;-)
```\$t1 = Get-Date
\$t2 = [DateTime]\$t1.ToLongTimeString()
\$t1 | Select-Object -Property *
\$t2 | Select-Object -Property *\$t1 -eq \$t2```

Best regards,

(79,108,97,102|%{[char]\$_})-join''

• Edited by Tuesday, April 3, 2018 11:59 PM
• Marked as answer by Wednesday, April 4, 2018 12:31 AM
Tuesday, April 3, 2018 11:19 PM

### All replies

• It is not equal because it is not equal.  ;-)
```\$t1 = Get-Date
\$t2 = [DateTime]\$t1.ToLongTimeString()
\$t1 | Select-Object -Property *
\$t2 | Select-Object -Property *\$t1 -eq \$t2```

Best regards,

(79,108,97,102|%{[char]\$_})-join''

• Edited by Tuesday, April 3, 2018 11:59 PM
• Marked as answer by Wednesday, April 4, 2018 12:31 AM
Tuesday, April 3, 2018 11:19 PM
• One way around this could be to limit the accuracy of the datetime value you get from Get-Date like this:
```\$t0 = Get-Date
\$t1 = Get-Date ([LONG]([MATH]::FLOOR(\$t0.Ticks / 10000000) * 10000000))
\$t2 = [DateTime]\$t1.ToLongTimeString()
\$t1 | Select-Object -Property *
\$t2 | Select-Object -Property *

\$t1 -eq \$t2
```

Best regards,

(79,108,97,102|%{[char]\$_})-join''

Tuesday, April 3, 2018 11:59 PM
• Easiest way to get an equal match to the second.

```\$t1 = Get-Date
\$t2 = [DateTime]'18:10:57'
if(\$t1.TimeOfDay.TotalSeconds -eq \$t2.TimeOfDay.TotalSeconds){
# times are equal
}else{
# times are not equal
}
```

It can be matched to hours, minutes, seconds or milliseconds.

The same construct can do a match within a simple range.

(\$t1.TimeOfDay.TotalSeconds - \$t2.TimeOfDay.TotalSeconds) -lt 10

Will match within 10 seconds.

\_(ツ)_/

• Proposed as answer by Wednesday, April 4, 2018 6:16 AM
Wednesday, April 4, 2018 12:56 AM
• At least much easier to read/understand than mine.  ;-)

Best regards,

(79,108,97,102|%{[char]\$_})-join''

Wednesday, April 4, 2018 6:16 AM