Windows 批处理 : formatted date into variable

标签 windows batch-file

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

Unix shell 模拟:

today=`date +%F`
echo $today

最佳答案

您可以使用与语言环境无关的方式获取当前日期

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

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

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

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

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

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

如果您需要 UTC 而不是本地时间,命令或多或少是相同的:

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

关于Windows 批处理 : formatted date into variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10945572/

相关文章:

c# - 为 BLE windows 8.1 开发

windows - MobaXterm 拖放面板丢失

linux - 网络接口(interface)名称的长度可以是多少?

batch-file - Windows Batch 将记录添加到主机文件

c# - "Property elements cannot be in the middle of an element' s 内容。”WPF 应用程序中的错误

scripting - 可以通过 Windows 登录脚本设置系统环境变量吗?

windows - 如何在批处理文件中(递归地)分割目录地址?

batch-file - 在批处理中读取具有特殊字符的文件

windows - 通过 Windows 资源管理器传递环境变量

windows - 我怎样才能告诉 Windows XP/7 在我的代码的特定段期间不要切换线程?