如何批量获取当前日期 - 1, -2 ,-3 , -4

How to get Current Date - 1, -2 ,-3 , -4 in Batch

这就是我想做的事情:

  1. 获取当前日期,这很容易 --- %DATE%
  2. DO Current Date - 1,我尝试了不同的选项,但似乎无法获得。

我想获取当前日期的最后 4 个日期,然后将它们存储在 4 个不同的变量中。然后将这些日期中的每一个转换成 YYYYMMDD 格式。

所以 %DATE% 给我 06/04/2016..... %DATE%

-1 should give me 05/04/2016 stored in Variable say Date1........
-2 should give me 04/04/2016 stored in Variable say Date2........
-3 should give me 03/04/2016 stored in Variable say Date3........
-4 should give me 02/04/2016 stored in Variable say Date4........ 

然后我想将存储在每个变量中的值转换为 YYYYMMDD

例如:

05/04/2016 to 20160405 ....
04/04/2016 to 20160404 ....
03/04/2016 to 20160403 ....
02/04/2016 to 20160402 ....

在 powershell 的帮助下:

@echo off
for /l %%d in (0,1,4) do (
    for /f "tokens=*" %%i in ('powershell get-date -date $(get-date^).adddays(-%%d^) -format yyyyMMdd') do set _Date%%d=%%i
) 
set _date

解释(从 TessellatingHeckler 的评论中逐字复制 - 无法更好地表述):

for /L is a batch file loop which counts numbers, 1 2 3 4, and each time through it calls PowerShell script engine with a for /f command which is a bit of a batch file workaround. The PowerShell command gets the current date, adds -X days to it, then gets the resulting date, and formats it in the way you want and returns it to the batch file, which gets one line of text back, and uses that in the do section to set the environment variable. tokens=* tells the loop not to split the line of text up, and the ^ are to escape special characters in batch files

for /l 是这样工作的:for /l %%i in (<start>, <step>, <end>)。在其他语言中,它会读成 FOR i=<start> TO <end> STEP <step>

powershell 命令汇编如下:

get-date - 获取今天的日期。

get-date -date <some date>得到<some date>的日期(看似荒唐,其实就是"take the string <some date> and convert it to a valid date")。

现在用 $(get-date).adddays(x) 替换 <some date> - 这意味着 "take today, and add x days"

最后一步是使用 -format <formatstring>

将结果日期格式化为所需的格式

你可以从 cmd 阅读 powershell 的帮助 powershell get-help get-date 或更详细:powershell Get-Help Get-Date -Online