获取系统时间的最佳批处理

使用批处理获取时间时,通常%DATE%来获取,但这个格式是受系统限制, 使用下面的方法获取系统时间就不用考虑格式的变化

 1 @echo off
 2 call :GetLocaldatetime
 3 echo %GetLocaldatetime%
 4 
 5 call :GetUTCTime
 6 echo %GetUTCTime%
 7 
 8 call :GetTimeZone
 9 echo %GetTimeZone%
10 
11 exit/b
12 
13 :GetLocaldatetime
14 for /f %%i in ('wmic os get localdatetime ^| find "."') do set dts=%%i
15 set GetLocaldatetime=%dts:~0,8%_%dts:~8,10%
16 exit /b
17 
18 :GetUTCTime
19 FOR /F "usebackq tokens=1,2 delims==" %%i IN (`wmic path win32_utctime get /format:list^|find "="`) DO (
20   if "%%i" EQU "Year" set YY=%%j
21   if "%%i" EQU "Month" set MM=%%j
22   if "%%i" EQU "Day" set DD=%%j
23   if "%%i" EQU "Hour" set HH=%%j
24   if "%%i" EQU "Minute" set MI=%%j
25   if "%%i" EQU "Second" set SS=%%j
26   if "%%i" EQU "DayOfWeek" set DW=%%j
27 )
28 if %MM% LSS 10 set MM=0%MM%
29 if %DD% LSS 10 set DD=0%DD%
30 if %HH% LSS 10 set HH=0%HH%
31 if %MI% LSS 10 set MI=0%MI%
32 if %SS% LSS 10 set SS=0%SS%
33 
34 if "%DW%" EQU "1" set DWS=MON
35 if "%DW%" EQU "2" set DWS=TUE
36 if "%DW%" EQU "3" set DWS=WED
37 if "%DW%" EQU "4" set DWS=THU
38 if "%DW%" EQU "5" set DWS=FRI
39 if "%DW%" EQU "6" set DWS=SAT
40 if "%DW%" EQU "7" set DWS=SUN
41 
42 set UTCDATE=%YY%%MM%%DD%
43 set UTCTIME=%HH%%MI%%SS%
44 set GetUTCTime=%UTCDATE%_%UTCTIME%_%DWS%_UTC0
45 exit /b
46 
47 :GetTimeZone
48 FOR /F "usebackq tokens=1,2 delims==" %%i IN (`powershell.exe -command Get-TimeZone^|find "DisplayName"^|grep -Eo "UTC.[0-9]{1,2}.[0-9]{1,2}"`) DO (
49   set GetTimeZone=%%i
50 )
51 set GetTimeZone=%GetTimeZone::=.%
52 exit /b

 

posted @ 2020-02-12 11:27  1CM  阅读(555)  评论(0编辑  收藏  举报