Format date and time in a Windows batch script Format date and time in a Windows batch script windows windows

Format date and time in a Windows batch script


I ended up with this script:

set hour=%time:~0,2%if "%hour:~0,1%" == " " set hour=0%hour:~1,1%echo hour=%hour%set min=%time:~3,2%if "%min:~0,1%" == " " set min=0%min:~1,1%echo min=%min%set secs=%time:~6,2%if "%secs:~0,1%" == " " set secs=0%secs:~1,1%echo secs=%secs%set year=%date:~-4%echo year=%year%

:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH

set month=%date:~4,2%if "%month:~0,1%" == " " set month=0%month:~1,1%echo month=%month%set day=%date:~0,2%if "%day:~0,1%" == " " set day=0%day:~1,1%echo day=%day%set datetimef=%year%%month%%day%_%hour%%min%%secs%echo datetimef=%datetimef%


Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):

@ECHO OFF:: Check WMIC is availableWMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error:: Use WMIC to retrieve date and timeFOR /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 _yyyy=%%L      Set _mm=00%%J      Set _dd=00%%G      Set _hour=00%%H      SET _minute=00%%I      SET _second=00%%K):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%Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%goto make_dump:s_errorecho WMIC is not available, using default log filenameSet logtimestamp=_:make_dumpset FILENAME=database_dump_%logtimestamp%.sql...


@ECHO OFF: Sets the proper date and time stamp with 24Hr Time for log file naming: convention ('YYYYMMDD_HHMMSS'): Scrapes the characters out of their expected permissions in the date/time: environment variables.: Expects a date format of '____MM_DD_YYYY': Expects a time format of 'HH:MM:SS' or ' H:MM:SS'SET HOUR=%time:~0,2%SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2% SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)ECHO %dtStamp%PAUSE