Getting a proper DATE variable in batch files

Windows batch files are hideous things, if one is used to *nix shell scripting. Everything feels wrong! Of course, that’s mostly just because they have a different syntax… but sometimes it’s because they are wrong.

Date formatting, for instance.

There’s an environment variable, %DATE%, that holds the current date, but it’s formatted to the current locale’s ‘short date’ definition, and so does not produce a consistent output from system to system.

Something as simple as naming files becomes a hideous contortion of detecting formats, splitting strings apart, and hopefully re-joining them in the right order. Too annoying for me, today, so I’ve taken a leap out of cmd and into java:

Firstly, compile the following Java class.

import java.text.SimpleDateFormat;
import java.util.Date;

public class date {

    public static void main(String[] args) {
        Date date = new Date();
        String out = new SimpleDateFormat("yyyy-MM-dd").format(date);
        System.out.println(out);
    }
}
$ javac thedate.java

Then, call it from a batch file with something like this:

echo off
setlocal
java date > thedate.txt
set /p THEDATE= < thedate.txt
del thedate.txt
echo The date is %THEDATE%
endlocal

This is ridiculous, yes, but it does at least work.