16 Jun 2020

Get Current Date and Time in Batch

收藏到CSDN网摘
From time to time, we may need to get the current date and time in batch to automate some tasks. For instance, I am modifying the compiled programme names using the current date, which is easy to archive and search in the future. There are such DOS commands exist such as Date and Time, which you can use to retrieve or set the current date and time respectively. However, we may like to get all this information in one go and manipulate it as required. If you're on Windows like me, the Windows Management Instrumentation (WMI) Command line tool (WMIC.exe) could be used for this purpose. The following batch shows how to get the date and time information and use them as variables in the batch.
::@Echo off
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
      Set _mm=00%%J
      Set _second=00%%K
      Set _yyyy=%%L
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%
      Set _second=%_second:~-2%

:: Display the date/time in ISO 8601 format:
Set _isodate=%_yyyy%-%_mm%-%_dd% %_hour%:%_minute%:%_second%
Echo %_isodate%

GOTO:EOF

:s_error
Echo GetDateTime.cmd
Echo Displays date and time independent of OS Locale, Language or date format.

Echo:
Echo Returns 6 environment variables containing ISO date: Year, Month, Day, Hour, Minute, and Second.
Based on the sorted date code by Rob van der Woude.

No comments :

Post a Comment