Windows 批处理:将日期格式化为变量 [英] Windows batch: formatted date into variable

查看:53
本文介绍了Windows 批处理:将日期格式化为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 YYYY-MM-DD 格式的当前日期保存到 Windows .bat 文件中的某个变量中?

How do I save the current date in YYYY-MM-DD format into some variable in a Windows .bat file?

Unix shell 模拟:

Unix shell analogue:

today=`date +%F`
echo $today

推荐答案

您可以使用

for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined MyDate set MyDate=%%x

然后您可以使用子字符串提取各个部分:

Then you can extract the individual parts using substrings:

set today=%MyDate:~0,4%-%MyDate:~4,2%-%MyDate:~6,2%

另一种获取包含各个部分的变量的方法是:

Another way, where you get variables that contain the individual parts, would be:

for /f %%x in ('wmic path win32_localtime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%

比摆弄子字符串好得多,代价是污染你的变量命名空间.

Much nicer than fiddling with substrings, at the expense of polluting your variable namespace.

如果您需要 UTC 而不是本地时间,命令大致相同:

If you need UTC instead of local time, the command is more or less the same:

for /f %%x in ('wmic path win32_utctime get /format:list ^| findstr "="') do set %%x
set today=%Year%-%Month%-%Day%

这篇关于Windows 批处理:将日期格式化为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆