简体   繁体   中英

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.

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

单行转换和减法。

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

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.

扩展Mani Live的答案...以在常规批处理文件中使用:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM