How to Compare Dates in PowerShell (With Examples)


You can use the following methods in PowerShell to compare dates:

Method 1: Compare Two Dates

$date1 -lt $date2

This particular example checks if the date stored in the variable named $date1 is less than (i.e. “earlier than”) the date stored in the variable named $date2.

Method 2: Compare Date with Today

$date1 -lt (Get-Date)

This particular example checks if the date stored in the variable named $date1 is less than today’s date.

Note that you can use the following equality comparison operators to compare dates:

  • 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 examples show how to use these methods in practice.

Example 1: Compare Two Dates in PowerShell

Suppose that we have the following two dates in PowerShell:

  • $date1: 10-15-2024
  • $date2: 10-22-2024

We can use the following syntax to check if $date1 is less than (i.e. “earlier than”) $date2:

$date1 = "10-15-2024"
$date1 = "10-22-2024"

$date1 -lt $date2

The following screenshot shows how to use this syntax in practice:

compare two dates in PowerShell

The statement returns True since October 15, 2024 is indeed less than (i.e. “earlier than”) October 22, 2024.

Example 2: Compare Date with Today in PowerShell

Suppose that we would like to compare the following two dates in PowerShell:

  • $date1: 10-15-2024
  • Today’s date: 02-27-2024

We can use the following syntax to check if $date1 is less than (i.e. “earlier than”) today’s date:

$date1 = "10-15-2024"
$date1 -lt (Get-Date)

The following screenshot shows how to use this syntax in practice:

PowerShell compare date with today

The statement returns False since October 15, 2024 is not less than (i.e. “earlier than”) today’s date of February 27, 2024.

If we’d like, we can also use the following syntax to get the date difference between 10-15-2024 and today’s date:

$date1 = "10-15-2024"

#get date difference
$date_diff = (Get-Date $date1) - (Get-Date)

#view date difference in days
$date_diff.Days

The following screenshot shows how to use this syntax in practice:

The $date_diff variable displays the date difference between 10-15-2024 and today’s date.

By using $date_diff.Days, we are able to view the date difference in terms of number of days.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: Get List of Files Modified After Certain Date
PowerShell: Check if File Has Been Modified in last 24 Hours

Leave a Reply