How to Calculate Date Difference in PowerShell (With Examples)


You can use the following basic syntax to calculate the difference between two dates in PowerShell:

$date_diff = New-TimeSpan -Start $date1 -End $date2

This particular example calculates the difference between the starting date stored in the $date1 variable and the ending date stored in the $date2 variable.

Note that we store the results in a new TimeSpan variable named $date_diff.

The following example shows how to use this syntax in practice.

Example: How to Calculate Date Difference in PowerShell

Suppose that we create the following date variables in PowerShell:

  • $date1 : The current date
  • $date2: The current date plus 50 days

We can use the following syntax to calculate the difference between the two dates:

$date1 = Get-Date
$date2 = (Get-Date).AddDays(50)

$date_diff = New-TimeSpan -Start $date1 -End $date2

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

PowerShell calculate date difference

The new $date_diff variable contains the date difference between the start and end dates that we specified.

We can see that the difference between the two dates is 50 days, 0 hours, 0 minutes, 5 seconds and 824 milliseconds.

If we would like to access only one of these units of time, we can do so.

For example, we can use the following syntax to only return the date difference in days:

$date1 = Get-Date
$date2 = (Get-Date).AddDays(50)

$date_diff = (New-TimeSpan -Start $date1 -End $date2).Days

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

We can see that the date difference between these two dates is 50 days.

Note: Feel free to replace Days with Hours, Minutes, Seconds, etc. to access a different unit of time.

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

Leave a Reply