Joey
Joey

Reputation: 509

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.

Upvotes: 11

Views: 57452

Answers (6)

MarredCheese
MarredCheese

Reputation: 20791

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"

Upvotes: 0

LReeder14
LReeder14

Reputation: 618

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

Upvotes: 5

Tom Warfield
Tom Warfield

Reputation: 776

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

Upvotes: 1

Mani Live
Mani Live

Reputation: 178

Single line conversion and subtraction.

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

Upvotes: 10

Farhad Farahi
Farhad Farahi

Reputation: 39237

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.

Upvotes: 0

StephenP
StephenP

Reputation: 4081

"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.

Upvotes: 22

Related Questions