views:

607

answers:

3

I'm writing a bat script and I have to save the date from a file to a variable. How can I do that?

I will use the variable to check wether the file is older than N days, so it would be nice to save the date in a format that would allow me to do such test.

+2  A: 

Date manipulation in batch files it nearly impossible to get right in a sensible way. The only thing you can do is support your culture and ignore the rest.

However, if you have the name of the file in a parameter to the batch (or a subroutine), you can use %~t1. Otherwise the following:

for %%x in (%file%) do set datetime=%%~tx

On my machine this comes out as "2009-08-28 16:13" which can then be parsed into its individual parts:

:dissect_date_time
for /f "tokens=1-5 delims=-: " %%a in (%1) do set year=%%a&set month=%%b&set day=%%c&set hour=%%d&set minute=%%e
goto :eof

this is a subroutine you can call with

call :dissect_date_time %datetime%

and then you have the individual parts in their respective environment variables. Adapt accordingly to suit your date/time format. This one makes heavy use of for as a tokenizer.

Once you have the individual parts you can try figuring out how old the file is by simply doing the same process with the current date/time and subtracting. Won't be much fun, but works.

Joey
+1  A: 

Here is a batch file that "Delete files older than N days from a single folder".

Replace the delete with whatever you need to do.

wierob
That batch, and especially the date dissection part, is evil :-)
Joey
+1  A: 

The batch command language is not really up to the task. Microsoft suggests PowerShell.

Microsoft Windows PowerShell command line shell and scripting language helps IT professionals achieve greater control and productivity. Using a new admin-focused scripting language, more than 130 standard command line tools, and consistent syntax and utilities, Windows PowerShell allows IT professionals to more easily control system administration and accelerate automation. Windows PowerShell is easy to adopt, learn, and use, because it works with your existing IT infrastructure and existing script investments, and because it runs on Windows XP, Windows Vista, and Windows Server 2003.

For a discussion of a similar task using PowerShell, see powershell-script-to-delete-old-files.

gimel
Or, in general, delegate the task to a scripting language.
Steve Gilham