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.
1 2 3 4 5 6 7 8 9 10 11 | 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:
1 2 3 4 5 6 7 | 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.
[Keywords: batch files, cmd, date formatting, dates, DOS, Java, variables, Windows] [One comment] [Permanent link]
Wow! This website is amazing! How did you make it look this good !?
[permalink]