Page 1 of 1

BATCH PROGRAM to GET DATE and TIME from FILE

Posted: Mon Dec 30, 2013 8:40 pm
by DavidRoper
Anybody know how to get the file date using a Windows Batch file? Such as YYYYMMDD and maybe time of file as HHMMSS? Not the system file and date, the File Time and date.

Re: BATCH PROGRAM to GET DATE and TIME from FILE

Posted: Tue Dec 31, 2013 2:31 pm
by SYSTEM
This should get you started. It returns both date and time, in a format that depends on regional settings.

Code: Select all

set FILE="foo"
for /F "delims=" %%i in ("%FILE%") do @echo %%~ti

Re: BATCH PROGRAM to GET DATE and TIME from FILE

Posted: Tue Dec 31, 2013 3:56 pm
by DavidRoper
Thanks, can you go further to give me year, month, day and 24hour, minute, and seconds as YYYY,MM,DD and then HH,MM,SS.
II need to use it to rename a file like YYYYMMDD-HHMMSS.txt., etc.

Re: BATCH PROGRAM to GET DATE and TIME from FILE

Posted: Wed Jan 01, 2014 2:07 am
by SYSTEM
That can be done by parsing the date/time string. How to do it depends on regional settings. For example, in Finnish Windows the date/time format is "DD.MM.YYYY HH:MM" (24-hour clock), e.g. "31.12.2013 23:59".

In the example below, %%a=DD, %%b=MM, %%c=YYYY, %%d=HH and %%e=MM.

Code: Select all

set FILE="foo"
for /F "delims=" %%i in ("%FILE%") do set DATE=%%~ti
for /F "tokens=1,2,3,4,5 delims=.: " %%a in ("%DATE%") do echo %%c,%%b,%%a %%d,%%e
The parts that can vary are the delimiters (dot, colon and space in Finland) and the order of date/time components.

----

If you need ability to do anything complex, seconds from file time, or independence from regional settings, I recommend using something other than batch files. Some alternatives:
  • If you only need to rename, DropIt may fit the bill.
  • Other scripting languages: I use Ruby for anything that involves loops. ;)
  • AutoIt/AutoHotkey: These allow you to "compile" the script (in reality, encrypt the script and bundle it with the interpreter) into a single .exe file.
  • Native code (such as C++): the hardest option, but also the most powerful.