PowerShell: How to Subtract Days from Date


You can use the following methods in PowerShell to subtract a specific number of days from a date variable:

Method 1: Subtract Days from Date

(Get-Date $my_date).AddDays(-1)

This particular example subtracts one day from the date specified in the $my_date variable.

Method 2: Subtract Days from Date and Format the Result

(Get-Date $my_date).AddDays(-1).ToString("MM/dd/yyyy")

This particular example subtracts one day from the date specified in the $my_date variable and formats the resulting date using a MM/dd/yyyy format.

The following example shows how to use these methods in practice.

Example 1: How to Subtract Days from Date in PowerShell

Suppose that we have the following date variable in PowerShell:

  • $my_date: 10/22/2023

Suppose that we would like to subtract one day from the date stored in this date variable.

We can use the following syntax to do so:

$my_date = "10/22/2023"
(Get-Date $my_date).AddDays(-1)

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

PowerShell subtract days from date

We can see that this returns October 21, 2023, which is one day before the date stored in our date variable.

Note: By providing a value of -1 to the AddDays method, we were able to subtract one day. If you would like to subtract a different number of days, simply provide a different negative number to the AddDays method instead.

Example 2: How to Subtract Days from Date and Format the Result in PowerShell

Once again, suppose that we have the following date variable in PowerShell:

  • $my_date: 10/22/2023

Suppose that we would like to subtract one day from this date and format the result using a MM/dd/yyyy format.

We can use the following syntax to do so:

$my_date = "10/22/2023"
(Get-Date $my_date).AddDays(-1).ToString("MM/dd/yyyy")

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

PowerShell subtract days from date and format result

We can see that this returns 10/21/2023, which is one day before the date stored in our date variable, formatted in the MM/dd/yyyy format that we specified.

Note: Refer to this tutorial for a complete list of date formats that you can use in PowerShell.

Related Tutorials

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

How to Compare Dates in PowerShell
How to Get Date Without Time in PowerShell
How to Calculate Date Difference in PowerShell

Leave a Reply