Search code examples
batch-filetimecopy

get time as hh:mm:ss in windows batch file


I have a batch file which is trying to copy a source file to a different directory, but also appending the date and time to the file name. Example command that I have is below.

copy /Y c:\apps\BIDW\Sf_Calls.txt      c:\apps\CDW\SF_CDWCalls_%date:~-4,4%%date:~7,2%%date:~-10,2%_%time:~0,2%%time:~3,2%.txt

However, this command is failing and after some debugging I came to know that time is not parsed correctly. Date gets parsed as 08 for the month, whereas if I run the above command at 7 AM, time is not getting parsed as 07, but only 7 as a result, the destination file name becomes SF_CDWCalls_20180814_ 730 and hence the above copy command is failing with the error message "Invalid Syntax".

Is there a way to get the time as 07:30 using the %time% variable in windows batch file? I see that the time command doesn't support much options.


Solution

  • Did you happen to notice the whitespace between the last _ and 730 which is caused by the whitespace in the %time% variable? You will see it when running echo %time% a leading space 7:30:23,40

    So Conditionally replace the leading space with a 0. This will only affect single digit hh

    echo %time: =0%
    

    So in your script, do this:

    set "tmptime=%time: =0%"
    copy /Y "c:\apps\BIDW\Sf_Calls.txt" "c:\apps\CDW\SF_CDWCalls_%date:~-4,4%%date:~7,2%%date:~-10,2%_%tmptime:~0,2%%tmptime:~3,2%.txt"