[DOS] 利用WMI 獲得日期和時間

利用Batch 將檔案備份是平常事, 然而若要重新命名檔案並加入日期的話, 因為本身沒有global variable 做, 而且還有地區設定等因素, 故事情變得複雜起來. 若要讀取日期時間的話, 除了用Data /t 外, 還可以透過WMI 進行.

@echo off
for /f "skip=1" %%x in ('wmic os get localdatetime') do if not defined currentDate set currentDate=%%x
set year=%currentDate:~0,4%
set month=%currentDate:~4,2%
set date=%currentDate:~6,2%
set hour=%currentDate:~8,2%
set minute=%currentDate:~10,2%
set second=%currentDate:~12,2%


echo Day of month : %date%
echo Month : %month%
echo hour : %hour%
echo minute : %minute%
echo second : %second%
echo year : %year%

利用WMI query, 將日期時間變為一段raw formatted string, 並利用substring 形式選取相對應的資料.

更新@06-Dec-2018

其實可以透過WMI Query進行直接存取日期時間, 從而避免不同日期格式時存取錯誤.

echo off
for /f %%# in ('wMIC Path Win32_LocalTime Get /Format:value') do @for /f %%@ in ("%%#") do @set %%@

echo Year: %year%
echo Month: %month%
echo Day: %day%
echo Hour: %hour%
echo Minute: %minute%
echo Second:%second%
echo Day of week: %DayOfWeek%
echo Quarter: %quarter%
echo Week in month: %weekinmonth%

執行結果:

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.