CMD/BATCH - Had to run batch script 3 times to get full result

111 views Asked by At
@echo off
REM returns current date and time as var datestamp in YYYYMMDD_hhmm format
REM         current date as variable date in YYYYMMDD format
REM         current time as variable time in hhmm format
for /f "tokens=2,3,4 delims=/ " %%a in ('DATE /T') do set date=%%c%%a%%b
for /f "tokens=1,2 delims=: " %%a in ('TIME /T') do set hr=%%a
for /f "tokens=1,2 delims=: " %%a in ('TIME /T') do set mi=%%b
for /f "tokens=1,2,3 delims=: " %%a in ('TIME /T') do set ampm=%%c
set time=%hr%%mi%

IF %ampm% EQU PM ( 
    REM in case of 12 PM we don't need to perform any actions
    IF %hr% EQU 12 GOTO end
    REM in case of another hour 1-11 PM we need to reformat it to 24-hour format by adding 12 hours
    set /A hour=1%hr%+12-100
    set time=%hour%%mi%
) ELSE (
    REM only in case of 12 AM we need to reformat it to 24-hour format by extracting 12 hours (00 hours)
    IF %hr% EQU 12 (
        set /A temp=1%hr%-12-100
        set hour=0%temp%
        set time=%hour%%mi%
    )
)
GOTO end
:end
set datestamp=%date%_%time%

This is just the script which generates date-time in 24-hour format (maybe here is some better way to do that). However it does not work. I had to run it 3 times before it shows complete results:

D:\utils\scripts>getDateStamp.cmd & echo %datestamp%
%datestamp%

D:\utils\scripts>getDateStamp.cmd & echo %datestamp%
20150609_55

D:\utils\scripts>getDateStamp.cmd & echo %datestamp%
20150609_1855

What might be the problem here? Thanks!

0

There are 0 answers