windows 如何在BAT文件中获取日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19131029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:57:42  来源:igfitidea点击:

How to get date in BAT file

windowsbatch-file

提问by Jacek

I need to get today date in Window *.batfile. After it I would like to get day, month and year. How can I do this?
I can't use PowerShell

我需要在 Window*.bat文件中获取今天的日期。之后我想得到日、月和年。我怎样才能做到这一点?
我无法使用 PowerShell

回答by foxidrive

This will give you DD MM YYYY YY HH Min Secvariables and works on any Windows machine from XP Pro and later.

这将为您提供DD MM YYYY YY HH Min Sec变量并适用于 XP Pro 及更高版本的任何 Windows 计算机。

@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"

set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause

回答by Ozan Yurtseven

You get and format like this

你得到并格式化这样

for /f "tokens=1-4 delims=/ " %%i in ("%date%") do (
     set dow=%%i
     set month=%%j
     set day=%%k
     set year=%%l
)
set datestr=%month%_%day%_%year%
echo datestr is %datestr%

回答by canhazbits

%date%will give you the date.

%date%会给你日期。

%time%will give you the time.

%time%会给你时间。

The dateand time /tcommands may give you more detail.

datetime /t命令可以给你更多的细节。

回答by Evaldas Jocys

Locale-independent one liner to get any date format you like. I use it to generate archive names. Back quote option is needed because PowerShell command line is using single quotes.

独立于语言环境的一个班轮以获得您喜欢的任何日期格式。我用它来生成档案名称。需要反引号选项,因为 PowerShell 命令行使用单引号。

:: Get date in yyyyMMdd_HHmm format to use with file name.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Get formatted yesterday date.
FOR /f "usebackq" %%i IN (`PowerShell ^(Get-Date^).AddDays^(-1^).ToString^('yyyy-MM-dd'^)`) DO SET DTime=%%i

:: Show file name with the date.
echo Archive.%DTime%.zip

回答by jfindley

set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause