Powershell Subtract 1 Day from Variable Date

How can I use a variable containing a date to act like get-date function in powershell? I have a variable $date containing 2016-09-08. I want to subtract one day from the $date. something like:

$date = "2016-09-08"
$date.AddDays(-1)

It doesn't work.

1

6 Answers

"2016-09-08" is a string. You need to convert it to a datetime object. There are several ways to do so but below is an example of passing a string to the Get-Date cmdlet.

$date = Get-Date "2016-09-08"
$date.AddDays(-1).ToString("yyyy-MM-dd")

See Custom Date and Time Format Strings for more details on all of the available options.

1

Single line conversion and subtraction.

(Get-Date $date).AddDays(-1)
0

This thread really helped me a lot and here's what I was trying to do. Sharing so others can see more things you can do with Get-Date and AddDays.

PS C:\Users\zzz> (Get-Date $date).AddDays(0).ToString("MMddyyyy")
07162019

PS C:\Users\zzz> (Get-Date $date).AddDays(-1).ToString("MMddyyyy")
07152019

Expanding on Mani Live's answer ... to use in a regular batch file:

for /F "usebackq" %%d in (`powershell -STA -ExecutionPolicy ByPass -command "echo ((Get-Date).AddDays(-10)).ToString(\"yyyy-MM-dd\")"`) do set ten_days_ago=%%d

Your variable is String. run $date.gettype() it will output string.

$date = "2016-09-08"
$date.gettype()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

to be able to use datetime functions you need a datetime variable.

$date = get-date("2016-09-08")
$date.gettype()
  IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Datetime                                   System.Object
$date.adddays(-1)
Wednesday, September 7, 2016 12:00:00 AM

then you can start using formatting of your choice.

You can also cast the string to a datetime:

$date = [datetime]"2016-09-08"

Or assign the string to a strictly-typed datetime variable:

[datetime]$date = "2016-09-08"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest