BATCH PROGRAM to GET DATE and TIME from FILE

Discuss anything related to command line tools here.
Post Reply
Message
Author
DavidRoper
Posts: 2
Joined: Mon Dec 30, 2013 8:16 pm

BATCH PROGRAM to GET DATE and TIME from FILE

#1 Post 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.

User avatar
SYSTEM
Posts: 2041
Joined: Sat Jul 31, 2010 1:19 am
Location: Helsinki, Finland

Re: BATCH PROGRAM to GET DATE and TIME from FILE

#2 Post 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
My YouTube channel | Release date of my 13th playlist: August 24, 2020

DavidRoper
Posts: 2
Joined: Mon Dec 30, 2013 8:16 pm

Re: BATCH PROGRAM to GET DATE and TIME from FILE

#3 Post 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.

User avatar
SYSTEM
Posts: 2041
Joined: Sat Jul 31, 2010 1:19 am
Location: Helsinki, Finland

Re: BATCH PROGRAM to GET DATE and TIME from FILE

#4 Post 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.
My YouTube channel | Release date of my 13th playlist: August 24, 2020

Post Reply