本文介绍了如何以特定格式获取昨天的日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以固定格式YYYYMMDD设置变量中的今天和昨天的日期.

I need to set Today and yesterday's date in a variable in a fixed format YYYYMMDD.

今天,当我这样做的时候

For today date, when i did

SET TODAY=%date:~10,4%%date:~4,2%%date:~7,2%

它正常工作并显示"20190426".但是如何设置昨天的日期,以便我以20190425的格式获取它?

it worked and displayed '20190426'.But how to set yesterday's date so I get it in the format - 20190425 ?

推荐答案

在SO上.

我建议您为此使用PowerShell一线式,您可以从批处理文件中调用它,如下所示:

I suggest you use a PowerShell one-liner for this, which you can call from a batch file as follows:

@echo off
for /f "usebackq delims=" %%A in (`
  powershell -NoP -C "'{0:yyyyMMdd}' -f (Get-Date).AddDays(-1)"
`) do set YESTERDAY=%%A

例如,当在2019年8月25日被调用时,

%YESTERDAY%将包含20190824.

%YESTERDAY% will then contain 20190824 when invoked on 25 August 2019, for instance.

稍长一些的变体,仅在一次PowerShell调用中同时包含了todayyesterday.

A slightly longer variant, incorporating both today and yesterday in only one PowerShell invocation.

:: Q:\Test\2019\04\26\SO_55862158.cmd
@echo off
for /f "usebackq delims=" %%A in (`
    powershell -NoP -C "'yesterday={0:yyyyMMdd}' -f (Get-Date).AddDays(-1);'today={0:yyyyMMdd}' -f (Get-Date)"
`) do set "%%A"

PowerShell部分发出两行

The PowerShell part issues two lines

yesterday=20190824
today=20190825

,由for /f解析并分别设置为环境变量yesterday/today.

which are parsed by the for /f and set as environment variables yesterday/today respectivly.

这篇关于如何以特定格式获取昨天的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 23:14