You can use the following basic syntax to compare two times in PowerShell:
$datetime1.TimeOfDay -lt $datetime2.TimeOfDay
This example assumes that $datetime1 and $datetime2 are both datetime variables and checks if the time of $datetime1 is less than (i.e. “earlier than”) the time of $datetime2, regardless of date.
Note that you can use the following equality comparison operators to compare times:
- lt: less than
- le: less than or equal to
- gt: greater than
- ge: greater than or equal to
- eq: equal
- ne: not equal
The following example shows how to compare two times in PowerShell in practice.
Example: How to Compare Two Times in PowerShell
Suppose that we create the following datetime variables in PowerShell:
- $datetime1 : The current time
- $datetime2: The current time plus two hours
We can use the following syntax to check if the time of $datetime1 is less than (i.e. “earlier than”) the time of $datetime2:
$datetime1 = Get-Date
$datetime2 = (Get-Date).AddHours(2)
$datetime1 -lt $datetime2
The following screenshot shows how to use this syntax in practice:

The statement returns True, which indicates that the time of the $datetime1 variable is indeed earlier than the time of the $datetime2 variable.
We can verify this is correct by looking at both datetimes:
- $datetime1: Thursday, February 29, 2024 9:00:10 AM
- $datetime2: Thursday, February 29, 2024 11:00:18 AM
The time of the $datetime1 variable is indeed earlier than the time of the $datetime2 variable.
If we’d like, we can use the following syntax to calculate the exact difference between the two times:
$datetime2 - $datetime1
The following screenshot shows how to use this syntax in practice:

We can see that the time of $datetime2 is 2 hours, 0 minutes and 7 seconds ahead of the time of $datetime1.
If we’d like, we can use the following syntax to extract just the difference in hours:
($datetime2 - $datetime1).Hours
The following screenshot shows how to use this syntax in practice:

This tells us that the time of $datetime2 is 2 hours ahead of the time of $datetime1.
Related Tutorials
The following tutorials explain how to perform other common tasks in PowerShell:
How to Compare Dates in PowerShell
How to Compare Two Arrays in PowerShell
How to Compare Two Strings in PowerShell
