如果解决方案要跨区域设置(即在具有不同区域设置的国际系统上)工作,则在命令行上确定日、月和年非常困难。虽然我们可以使用变量 %DATE% 和 %TIME%,但它们的内容特定于区域设置。如果设置为德语,则日期以 dd.MM.yyyy 格式显示;如果设置为"英语(美国)",则日期格式为 M/d/yyyy。
在网络上搜索,我发现了几种解决方案,其中最优雅的是依靠WMI来返回独立于区域设置的日期和时间。我下面的脚本是Rob van der Woude的脚本SortDate.bat的修改版本。
在脚本中,WMI 命令行工具 WMIC 用于分别获取年、月、日、小时、分钟和秒。在这些单独的值中,将构造格式化的日期和时间字符串。遗憾的是,WMI 不会返回毫秒,因此我们仅限于秒的分辨率。
脚本的输出如下所示:
C:\>FormattedDateTime.cmd
FormattedDate=2021-02-02
FormattedTime=02:03:02
当然,实际的格式可以很容易地改变。
下面是脚本 FormattedDateTime.cmd:
@echo off
::
:: Get date/time independent of system locale and regional settings
:: By Helge Klein
:: Based on code by Rob van der Woude (http://www.robvanderwoude.com/files/sortdate5_xp.txt)
::
setlocal ENABLEDELAYEDEXPANSION
:: Use WMIC to retrieve date and time
for /f "skip=1 tokens=1-6" %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do (
if not "%%~f"=="" (
set /A FormattedDate=10000 * %%f + 100 * %%d + %%a
set FormattedDate=!FormattedDate:~0,4!-!FormattedDate:~4,2!-!FormattedDate:~6,2!
set /A FormattedTime=10000 * %%b + 100 * %%c + %%e
set FormattedTime=0000000!FormattedTime!
set FormattedTime=!FormattedTime:~-6,2!:!FormattedTime:~-4,2!:!FormattedTime:~-2,2!
)
)
:: Display the results
set formatted
endlocal