sojim
sojim

Reputation: 502

Batch file: Get yesterday's date in format: M_d_yyyy

How does one get yesterday's date format in a batch file?

I'd like it to look like so: M_d_yyyy

Note that if there's a single digit day and month, I'd like it to be single digits.

Example: 8_5_2013 is August 5th, 2013.

I looked around for a few days but couldn't find a solution.. any lead is much appreciated.

Upvotes: 0

Views: 8303

Answers (2)

Mike Clark
Mike Clark

Reputation: 10136

I think you should get date.exe from UnxUtils.

date.exe --date="1 day ago" "+%-m_%d_%Y"

Download: http://sourceforge.net/projects/unxutils/files/unxutils/current/
Man page: http://www.ss64.com/bash/date.html


@echo off
setlocal
set magic="c:\unx\usr\local\wbin\date.exe" --date="1 day ago" "+%%-m_%%d_%%Y"
for /f %%i in ('%magic%') do set yesterdate=%%i
echo yesterdate = %yesterdate%

If you want to do it with just batch language, you'll end up with nearly 100 lines of incomprehensible batch code. UPDATE: or use dbenham's hybrid batch/JScript solution posted in the answer below, which at least uses sane Windows APIs.


See Also: How to get current datetime on Windows command line, in a suitable format for using in a filename?

Upvotes: 2

dbenham
dbenham

Reputation: 130839

Nothing wrong with free 3rd party executables, but some of us are not allowed to use them on our work machines.

I have written a powerful hybrid JScript/batch utility called getTimestamp.bat that can do nearly any date and time computation on a Windows machine.

There are a great many options for specifying the base date and time, many options for adding positive or negative offsets to the date and time, many options for formatting the result, and an option to capture the result in a variable. Both input and output can be directly expressed as local time, UTC, or any time zone of your choosing. Full documentation is embedded within the script.

The utility is pure script that will run on any modern Windows machine from XP forward - no 3rd party executable required.

Assuming getTimestamp.bat is in your current directory, or better yet, somewhere within your PATH, then the following simple call will define a dt variable containing yesterday's date in M_D_YYYY format:

call getTimestamp -od -1 -f {m}_{d}_{yyyy} -r dt

Note: when I put a date in a file name, I like to use YYYY_MM_DD format because that format will sort chronologically when getting a directory listing.

Upvotes: 3

Related Questions