Getting Yesterdays or Tomorrows Day With Bash Shell Date Command

by on June 17, 2007 · 61 comments· LAST UPDATED June 15, 2011

in , ,

When invoked without arguments, the date command displays the current date and time. Depending on the options specified, date will set the date and time or print it in a user defined way. I've seen many sysadmin writing perl scripts for calculating relative date such as yesterdays or tomorrows day. You can use GNU date command, which is designed to handle relative date calculation such as:

  • 1 Year
  • 2 Days
  • 2 Days ago
  • 5 Years

GNU date syntax

The syntax is as follows:

 
date  --date="STRING"
date  --date="next Friday"
date  --date="2 days ago"
 

The --date=STRING is a human readable format such as "next Thursday" or "1 month ago". A date string may contain items indicating calendar date, time of day, time zone, day of week, relative time, relative date, and numbers.

Why Use Relative GNU/date Formats?

  • Ease of use
  • Write your own shell scripts
  • Automate task using cron (example run a job on last day of the month or Nth day of the month or 3rd Friday and so on)

Examples

First, to display today's date, enter:
$ date
Sample outputs:

Wed Jun 15 04:47:45 IST 2011

To display yesterday's date, enter:
$ date --date="1 days ago"
OR
$ date --date="1 day ago"
OR
$ date --date="yesterday"
OR
$ date --date="-1 day"
Sample outputs:

Tue Jun 14 04:54:40 IST 2011

You can use various string formats to produce the same output. Please note that the output of the date command is not always acceptable as a date string, not only because of the language problem, but also because there is no standard meaning for time zone items like IST.

Find tomorrow's date

Type the following command
$ date --date="-1 days ago"
Or
$ date --date="next day"

Getting Date In the Future

To get tomorrow and day after tomorrow (tomorrow+N) use day word to get date in the future as follows:

 
date --date='tomorrow'
date --date='1 day'
date --date='10 day'
date --date='10 week'
date --date='10 month'
date --date='10 year'
 

The date string 'tomorrow' is worth one day in the future which is equivalent to 'day' string i.e. first two commands are same.

Getting Date In the Past

To get yesterday and earlier day in the past use string day ago:

 
date --date='yesterday'
date --date='1 day ago'
date --date='10 day ago'
date --date='10 week ago'
date --date='10 month ago'
date --date='10 year ago'
 

The date string 'yesterday' is worth one day in the past which is equivalent to 'day ago' string i.e. first two commands are same.

Moving By Whole Years or Months

You can add year and months keywords to get more accurate date:
$ date --date='2 year ago' # Past
$ date --date='3 years' # Go into future
$ date --date='2 days' # Future
$ date --date='1 month ago' # Past
$ date --date='2 months' # Future

Moving Date Using More Precise Units

  • You can use fortnight for 14 day.
  • week for 7 days.
  • hour for 60 minutes
  • minute for 60 seconds
  • second for one second
  • You can also use this / now / today keywords to stress the meaning.

Few examples using precise string units:

 
date --date='fortnight'
date --date='5 fortnight'
date --date='fortnight ago'
date --date='5 fortnight ago'
date --date='2 hour'
date --date='2 hour ago'
date --date='20 minute'
date --date='20 minute ago'
 

Moving Date Using the Day of Week Items

To print the date of this Friday, enter:

 
date --date='this Friday'
## OR ##
date --date='next Friday'
 

Days of the week may be spelled out in full: Sunday, Monday, Tuesday, Wednesday, Thursday, Friday or Saturday. Days may be abbreviated to their first three letters, optionally followed by a period

 
date --date='this Fri'
## OR ##
date --date='next Fri.'
 

You can also move forward supplementary weeks as follow:

 
date --date='2 Fri'
## OR ## 
date --date='second Fri.'
## OR ## 
date --date='Second Friday'
####
####  last DAY or next DAY move one week before or after the day that DAY by itself
####
date --date='last Friday'
date --date='next Friday'
 

To print the date in the future ($now + 6 months + 15 days), enter:
$ date --date='6 months 15 day'
To print the date in the past [$now - (two months and 5 days ago) ], enter:
$ date --date='-2 months 5 day ago'

Display Date Using Epoch Time

To display date in epoch time:
$ date --date='1970-01-01 00:00:01 UTC +5 hours' +%s

How Do I Use Relative Date Format To Set System Date & Time?

You can also use relative format to setup date and time. For example to set the system clock forward by 30 minutes, enter (you must be login as root to set the system date and time):
# date --set='+30 minutes'
OR
# date --set='1 day ago'
OR
# date --set='5 day'
However, I recommend setting NTPD client / server or OpenNTPD server to synchronize the local clock of a computer system with remote NTP servers.

How Do I Assigned Yesterday To Shell Variable?

Use the following syntax (see assign values to shell variables and command substitution for more information)

 
yest=$(date --date="yesterday")
echo "$yest"
yest=$(date --date="yesterday" +"%d/%m/%Y")
echo "The backup was last verified on $yest"
 

Recommend readings:

  1. man date
  2. GNU/date documentation

Updated for accuracy!

TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 61 comments… read them below or add one }

1 kiuze July 4, 2007 at 9:19 pm

Thank you for this info!

There seems to be a small typo on first example:

date –date=”1 days ago”

should be

date -–date=”1 days ago”

with two “-”s

Reply

2 Rajesh September 23, 2010 at 3:42 pm

Is there any way to caculate the current staturday’s date based on the input date passed not from the system date?

Please let me know
Thanks,
Rajesh

Reply

3 nixCraft July 4, 2007 at 9:55 pm

kiuze,

Thanks for the heads up!

Reply

4 Hebi-kai July 6, 2007 at 5:48 pm

How do you use the –date= string to start at one point and count ahead? I want to start at 20060108 and display the date of each sunday until July 1, 2007. If I say “–date=’week’” it gives me one week from today. How can I add ‘week’ to a date, such as 20060108?

Reply

5 Pablo Armando September 18, 2007 at 6:34 pm

You can use someting like this to:

$date -d “yesterday” +%d
$date -d “yesterday” +%m

or

$date -d “yesterday” +%m%d%y

Reply

6 Dharmendra Devireddy May 8, 2012 at 12:13 pm

Thank you..it is working :)

Reply

7 BK October 25, 2007 at 12:01 am

Given a date, how do I relatively find a day of the week? Example: For the date 20070807, how do I find out the date of the Monday of that week?

Reply

8 sai October 30, 2007 at 1:22 pm

how to find the dates between 2 dates.
i need a command to get the list of dates between 2 dates.

Reply

9 Sri November 30, 2007 at 6:56 am

Hi,
I want previous date and Next date.
I tried the above commands,byt its giving me the following usage.
bash-3.00$ date –date=”yesterday”
date: illegal option — -
Usage: date [-u] [+format]
date [-u] [mmddhhmm[[cc]yy]]
date [-a [-]sss.fff]

I am using HP-UX machine

Reply

10 Geneyo June 2, 2011 at 7:27 pm

I am having similar error on HP. How did you resovle your problem?

Reply

11 Dave February 1, 2012 at 3:10 pm

I do not think HP-UX uses the GNU tools, such as /bin/date.
You need more that just bash, presuming you typed “date –date=….”
In other words, “date {dash{dash} date=”
There are many little details like that which make HP-UX annoying.
I am spoiled by Linux.

Reply

12 Rd September 24, 2013 at 12:59 pm

It may not work for HP-UX. It is for Linux.

Reply

13 Deiva June 11, 2008 at 9:31 am

Excellent! Very useful while writing scripts.

Thanks!!

Reply

14 Omri A December 23, 2008 at 9:45 am

Or you can use the following to get tomorrow’s date:

x="`date '+%m'`"
y="`date '+%Y'`"
z="`date '+%d'`"
z="`expr ${z} + 1`"
cal ${x} ${y} | grep -w ${z} > /dev/null || {
        z="01"
        x="`expr ${x} + 1`"
        [ "${x}" -lt "10" ] && x="0${x}"
        [ "${x}" = "13" ] &+ 1`"
        }
}
[ "${1}" = "MMDDYYYY" -o "${1}" = "mmddyyyy" -o -z "${1}" ] &${z}${y}"
        echo ${tomorrow}
        exit 0
}
[ "${1}" = "DDMMYYYY" -o "${1}" = "ddmmyyyy" ] &${x}${y}"
} || {
        echo "Invalid format! Using the default:"
        tomorrow="${x}${z}${y}"
}
echo ${tomorrow}

Reply

15 Beniori February 10, 2009 at 3:15 am

It is very useful. However, I would like to know how can I type the end of month.

Reply

16 Andrew McGlashan March 15, 2009 at 4:46 pm

I’ve been wanting to work out last day of a month too. I just worked it out:

date -d ‘next month – ‘`date +%d`’day’

Cheers
AndrewM

Reply

17 Philippe Petrinko September 17, 2010 at 4:03 pm

@Andrew & @Sourav

May be wordpress word entry has eaten some of your characters,
here is an equivalent rephrase of what you gave,
to print last day of current month on GNU/BASH shell

date --date "next month - $(date +%d) day"

Reply

18 Sourav March 16, 2009 at 11:20 am

I am not sure, but when I am trying to use the above command:
date –date=”1 days ago”
I get the following error:
date: illegal option — -
date: illegal option — d
date: invalid argument — te=1 days ago
usage: date [-u] mmddHHMM[[cc]yy][.SS]
date [-u] [+format]
date -a [-]sss[.fff]
Just FYI: The flavour Unix, I am using is SunOS, and my shell is KORN Shell.

Reply

19 Jason Tepoorten March 19, 2009 at 12:27 am

Hi Sourav.

I don’t think the Solaris “date” command is as extensive as the LINUX date command.

I this informaiton from Solaris 10′s date command when using “date –date”:
$ date –date
date: illegal option — date
usage: date [-u] mmddHHMM[[cc]yy][.SS]
date [-u] [+format]
date -a [-]sss[.fff]
$

I found an article on getting yesterday’s date on Solaris from the shell. The article provides a PERL shell command:
perl -e ‘print scalar(localtime(time – 86400)), “\n”‘

The URL for that article is http://sysunconfig.net/unixtips/prevdate.txt

Reply

20 Jason Tepoorten March 19, 2009 at 1:10 am

Hi Sourav.

I’ve done some digging for determining yesterday’s and tomorrow’s date and I found a Korn Shell script posted at the URL http://www.computing.net/answers/unix/getting-old-date-into-variable/5223.html. Look for Response 10 for the source of the KSH script.

This KSH script runs under KSH on Solaris 10.

Reply

21 Sourav March 24, 2009 at 10:49 am

Hi Jason,

Firstly thanks a ton to find out the source of my problem.

But just FYI, i tried to give the below commands, and it helped me to get yesterday’s and tomorrow’s date. Hope this helps everyone who faces the same issue as me.

$ TZ=$TZ+24 date “+%D”……….for yesterday’s date
$ TZ=$TZ-24 date “+%D”………..for tomorrow’s date

Thanks again…

Reply

22 Jason TEPOORTEN May 30, 2010 at 12:50 am

Hi Sourav.
I apologise for the late reply. I never got a posting notification :(.
I’ll try this command on my client’s UltraSPARC IV SunOS 10.0 KSH environment.
How did you find this one?
Kind Regards,
Jason TEPOORTEN

Reply

23 Ibrahim July 12, 2009 at 2:55 pm

The “date –date” option only works with GNU version of date. It will most probably not work on AIX, Solaris or HP-UX. If you want to calculate yesterday’s date, you can also use this shell script.

Slight modification may be necessary to calculate tomorrow’s date.

Reply

24 'Tosin September 25, 2009 at 3:28 pm

Thanks so much, this has been so helpful.

Reply

25 Aleks November 18, 2009 at 5:15 pm

@Andrew McGlashan
thx a whole bunch!

Reply

26 Ibrahim Khaleel December 2, 2009 at 2:47 pm

I wanted output as this format – 2009_12_01, the below worked for yesterday
echo `date –date=”yesterday” ‘+20%y_%m_%d’`

Reply

27 Kassim May 18, 2010 at 7:18 am

How to find the commands which are executed yesterday?

Reply

28 Arthur July 14, 2010 at 7:22 am

@Kassim

Use the command

$ history

Reply

29 joi sagum September 13, 2010 at 2:42 am

How this this done in AIX?

Reply

30 Reynold P J November 6, 2010 at 11:34 pm

I usually find really helpful articles in this site….
Keep up the good work:)

Reply

31 bob March 1, 2011 at 12:11 am

doesn’t work on Mac OS X

Reply

32 Tom October 1, 2013 at 11:29 pm

for mac use -v-Xd (X days ago) example:

date -v-1d “+%Y-%m-%d”

Reply

33 Skyblaster March 24, 2011 at 3:14 pm

Hello guys,

Here is a nice one it calculate the latest working day of the month maybe it’s usefull
TODAY=`date +%d-%m-%Y`
if [ ${TODAYR} -eq 5 ]
then
DD2=`TZ=”GMT-72″ date +’%d’`
else
DD2=`TZ=”GMT-24″ date +’%d’`
fi
if [ ${DD} -gt ${DD2} ]
then
another script on the latest work day of the month

else

exit

Reply

34 Skyblaster March 24, 2011 at 3:16 pm

Hello guys,

(i missed the TODAYR (is day number from 1-7) in my prev email)
TODAY=`date +%d-%m-%Y`
TODAYR=`date +%u`
if [ ${TODAYR} -eq 5 ]
then
DD2=`TZ=”GMT-72″ date +’%d’`
else
DD2=`TZ=”GMT-24″ date +’%d’`
fi
if [ ${DD} -gt ${DD2} ]
then

Reply

35 seldi June 4, 2011 at 8:34 am

It was very helpfully for me.
Thanks

Reply

36 Nico June 8, 2011 at 1:05 pm

You have a little flaw in there:

date --date "2 months 5 days ago"

doesn’t return the date two months and five days ago but rather the date which was five days before the date which will be in two months. It tells date something like “plus 2 months minus 5 days”.

Of course, this might be what you wanted. But to be corresponding to your descripten, it would have to be

date --date "2 months ago 5 days ago"

Reply

37 Philippe Petrinko June 14, 2011 at 3:02 pm

Yes Rigth Nico.

Vivek should amend this one, right Vivek ?

Reply

38 nixCraft June 15, 2011 at 12:35 am

@Nico / Philippe,

This article has been updated with information on the date command with additional examples.

Reply

39 victor January 9, 2012 at 8:03 pm

It does work but it should look like:
date –date “-2 months 5 days ago”

Reply

40 Philippe Petrinko January 9, 2012 at 11:35 pm

Hi Victor.

I am afraid syntax is unclear to you.
Regarding each token (day, month) syntax may be either using minus sign, either using “ago” word. So that all 4 expressions are referring to one unique date:

date –date “2 months ago 5 days ago”
date –date “- 2 months – 5 days”
date –date “2 months ago – 5 days”
date –date “- 2 months 5 days ago”

Is it clear to you now?

– Philippe

Reply

41 jay June 13, 2011 at 9:57 pm

hello –

I am looking for some ideas to print out dates in between 2 dates in YYYY-mm-dd format in unix.

any advice is appreciated.

thanks

Reply

42 jay June 13, 2011 at 10:26 pm

for ((i=”2010-12-01″; i<="2011-06-14"; $currentDateTS+=86400))
do
echo $i"\n"
done

i know something is not right here please advice.

Reply

43 rani June 14, 2011 at 11:57 am

we are using this command in our pull script to get day-1 data.
vYdy_yyyy_mm_dd=`date –d=’1 days ago’ +”%Y-%m-%d”`
But i want data from 2010-08-1 to 2010-05-19 at a time.Could you please help me out in changing the command.
vYdy_yyyy_mm_dd=`date –d=’1 days ago’ +”%Y-%m-%d”`

Reply

44 Chunky October 10, 2011 at 2:28 pm

Hi all,

I am having a script to check filesize’s difference between two consecutive days dumps. The DB dumps are created every WORKING day (Monday-Friday) and they all have the same name + the full name day of the week, i.e. dumpFile.Monday.dump, dumpFile.Tuesday.dump … dumpFile.Friday.dump.

In my script I try to use `date +%A` for today and `date –date=yesterday +%A` for yesterday, however this (obviously) doesn’t work for Monday, when I get yesterday as being Sunday, whereas I want Friday.

I hacked a bit the script with an if loop, if today = Monday, then use yesterday = Friday, else use `date –date=yesterday +%A`, but is not quite an elegant solution.

I wonder if there’s a way that on any given date, to be able to get previous WORKING day.

Cheers

Reply

45 Philippe Petrinko January 10, 2012 at 10:18 am

Hi Chunky,
You post is old, but here is an answer.

Any system can only elaborate data based on what you feed it with, data & algorithm.
A “working day” is a humain professional concern, and, AFAICS, this information is not stored _yet_ in any standard *nix system.

hacked a bit the script with an if loop, if today = Monday, then use yesterday = Friday, else use `date –date=yesterday +%A`, but is not quite an elegant solution.

Elegant or not, system has to store this information before giving it back to you.

FTTOMH, as you want to compare the 2 most recent dump files, another way to do it without this worrying about working days would simply be to select the 2 most recent dump files to compare them, based on modification time.

Nevertheless, on one hand, this involves at least extra coding instead of a simple test, and may be less secure, for instance if you do not check that every dump went fine.

On the other hand, this algorithm would work in any situation, that is, it would always test the 2 most recent dump files, whatever calendar events, closing days, holidays, whatsoever.

What do you think Chunky?

– Philippe

Reply

46 Divya March 2, 2012 at 6:31 am

Hey I make a query..please let me know if this is possible…
StartDate=`date –date=’1 day ago’ +”%y%m%d”`

i am using above command to use yesterday’s date. In “1 day ago” i want to make 1 as variable like $i to change it when needed. as 1,2,3 etc…

Reply

47 hroptatyr April 20, 2012 at 9:59 am

Hey Chunky,
here’s another take on your problem if you can afford to have an extra binary that does the job. Look at my dateutils project (http://hroptatyr.github.com/dateutils). It can deal with business days natively, use the b suffix:

dadd 2012-04-16 -1b
=> 2012-04-13

Reply

48 qcjn October 28, 2012 at 5:33 am

date –date “3 month – $(date +%d) day + 1 day”
tried it using Philippe Petrinko and adding one day, this show the first day of the mont in 3 month. Just to show how much you can do.
date -d ‘-3 days -2 hours -10 minutes’ ‘+%d/%m/%Y %H:%M’ , this second part changes the format.
Thanks for this tutorial

Reply

49 Melanie November 5, 2012 at 4:53 pm

I found that when the clocks are set back an hour in November, here in the US, I could not use 1 day ago in the date command and have to use 26 hour ago. If you don’t do that you could accidentally work with the wrong file.

Reply

50 Martin March 1, 2013 at 6:38 pm

Just beautiful…

Reply

51 kokosny July 31, 2013 at 11:18 pm

for bsd users, to get yesterdays date or any past or future date.
You can customize the format too.

yest=$(date -v-1d +”%m_%d_%Y” )

hope it helps

Reply

52 Kumar March 17, 2014 at 8:05 am

Im getting following error while copying file from one server to other , even tried by defining and passing a variable same error.

spawn scp  /var/backup/full_bkup-$(date --date "yesterday" +%Y%m%d).sql.tgz "root@IPAddress:/home/ravi
Error
"can't read "(date --date "yesterday" +%Y%m%d)": no such variable
    while executing
"spawn scp  /var/backup/full_bkup-$(date --date "yesterday" +%Y%m%d).sql.tgz "root@IPAddress:/home/ravi""
    (file "./script3.sh" line 5)

Thanks

Reply

53 Dipun April 8, 2014 at 4:25 pm

Hi,
I am just learning Unix script and i started to write shell script.
I want to see 7days back date from current date format should be mm/dd/yyyy.
Could you please help me.

Thanks
Dipun Rath

Reply

54 Nick April 27, 2014 at 6:21 pm

Hi Dipun,
Welcome to shell scripting! Using bash and sh, I believe this should get you what you’re looking for.

date -v -7d +”%m/%d/%Y”

Hope this helps

Reply

55 Abhilash Kumar April 24, 2014 at 12:31 pm

date -v -1d

In order to get 1 day back date using date command:
date -v -1d
It will give (current date -1) means 1 day before .
date -v +1d
This will give (current date +1) means 1 day after.

Similarly below written code can be used in place of “d” to find out year,month etc
y-Year,
m-Month
w-Week
d-Day
H-Hour
M-Minute
S-Second

Reply

56 Toh Chai Hou June 5, 2014 at 3:40 am

Hi Guys,

I am new to this. Saw the email threads on having the dates. I am running Win7 platform. Would want to carry out a CCTV backup for previous day folder in YYYYMMDD folder. Can advise on the comandline please.

Reply

57 El Nico June 5, 2014 at 8:16 am

@Toh Chai Hou:
This is very linuxy here, so I guess you won’t get help about the Win7 platform. But you might start with a post like this.

Not even 10 seconds of googling.

Reply

58 Andrew Kendall June 13, 2014 at 9:38 am

I’ve got a requirement/variation not covered above (I think):
Using linux bash, how would I calculate the year for last month if this month is January?
Obviously for the Months Feb-Dec, the year for last month is the same as this month.
Would this work please?
date –date=’1 month ago’ +%Y
As it’s currently May it’s giving me the result I should get but I don’t have a system to play with where I can change the system date to confirm it works for January.
Thanks in advance,
Andy.

Reply

59 Philippe Petrinko June 25, 2014 at 2:11 pm

@Andy,

Yes,

date –date=”1 month ago” +%Y

would give you appropriate year for any month.

Used in january, you would definitely get previous year.

– Philippe

Reply

60 Andrew Kendall June 26, 2014 at 7:38 am

Thanks Pilippe. I’d given up on getting an answer.
Best regards
Andrew

Reply

61 Philippe Petrinko June 26, 2014 at 3:38 pm

My pleasure, @Andy

By the way, remember that you should test any code in a test environment, not on a production server. ;-)

-P-P

Reply

Leave a Comment

Tagged as: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Previous post:

Next post: