Format dates and times on DOS Command Prompt: How to extract substrings in DOS batch scripting

So its been a while since I have been looking for a way to do this. On the DOS command prompt, I need the date formatted as say dd-mm-yyyy or yyyy-mm-dd. How do you accomplish that? Its been a mystery for me for quite a while, till I read this excellent article and said “Thank You” out loud thrice over. :)

Screen shot of Command Prompt showing Date Formatting

So here’s the logic behind this:
%date:~-2,2%\%date:~0,2%\%date:~3,2%

DOS already stores the %DATE% system variable. So if you do a echo %date% DOS should give you the current date.

Depending upon the format of this output, you can customize the format of the date by using substrings. Lets take a closer look at the command string above. If you notice %date is appended by a colon(:) and a tilde(~). This is the syntax to extract a substring from the specified parameter (in this case the %date% output).

So when we do a echo %date:~3,2%, DOS returns us the substring from the output of %DATE% from character 4(3+1, remember DOS string indexes start from 0), extending for 2 characters, including the 4th character. You can use the negative symbol(-) to start from the end of the output of the date string, as %date:~-2,2 shows. It extracts 2 characters from the end of the output of %DATE%.

You can obviously try this technique out on different command texts like %TIME%, %DIR% and %SYSDIR% etc. to do a lot more than you could ever do.

In case you are wondering how could this possibly be helpful to anyone, ask System Administrators, Database Administrators and Data Warehousing Specialists, who frequently need to rename files based on the current date and time.

Note: I have tested this on 2 machines running Win XP Pro and 1 machine on Win 2000. It works fine on both. Other platforms still require testing

No Comments so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

(required)

(required)