Getting Yesterdays or Tomorrows Day With Bash Shell Date Command

Posted on in Categories Howto, Linux, Shell scripting, Tips, UNIX last updated June 17, 2007

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!

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 74 comments/add one below):

74 comment

  1. 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

  2. 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?

  3. 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

      1. 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.

  4. 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}
    
    1. @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"

  5. 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.

  6. 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

  7. 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…

  8. 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.

  9. 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

  10. 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

  11. 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"
      1. 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

  12. 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”`

  13. 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

    1. 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

  14. 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…

  15. 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

  16. 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.

  17. 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 "[email protected]:/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 "[email protected]:/home/ravi""
        (file "./script3.sh" line 5)
    

    Thanks

  18. 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

  19. 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

  20. 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.

  21. 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.

    1. @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

  22. Hi,

    I’m trying to find the date of Monday before a date.

    That is on the 05-Feb-2014, the Monday date was 03-Feb-2014.
    I have tried to:
    # date –date “last monday – $(date -d ‘2014-02-05’ +%d) day”
    Wednesday 30 July 00:00:00 EST 2014

    AND
    # date –date “$(date -d ‘2014-02-05’ +%Y%m%d) last monday”
    Wednesday 5 February 00:00:00 EST 2014

    But I want “Monday 3 February 00:00:00 EST 2014” which I can convert to 2014-02-03 (YYYY-MM-DD).

    Thank you in advance.

    Cheers
    Craig.

    1. @Craig

      For instance, I would proceed this way, using your specific date as a parameter

      1) determine which day of week is your parameter date (the date that your search for its previous monday)
      2) use (1) this to get back using the “days ago” expression date

      But take care! If parameter date is a monday, you have to get back 7 days ago.

      Show us what you could do this way! 🙂

      — Philippe Petrinko

  23. This probably could be a lot cleaner.

    #!/bin/bash
    #– dateconv.sh

    indate=$1
    checkday=`date –date=$(echo ${indate}) +%u`
    case ${checkday} in
    1) echo “Monday – Hooray — `date –date=$(echo ${indate} “+%c”)`”
    ;;
    *) indate=`expr ${indate} – ${checkday} + 1`
    checkday=`date –date=$(echo ${indate}) +%u`
    case ${checkday} in
    1) echo “Monday – 2nd Time — `date –date=$(echo ${indate} “+%c”)`”
    ;;
    * ) echo “Failed – ${checkday} – Should not happen.”
    ;;
    esac
    ;;
    esac
    echo “End Script”

    > dateconv.sh 20140205
    Monday – 2nd Time — Mon 03 Feb 2014 00:00:00 EST
    End Script

    Thanks Phillippe for your help.

  24. Thank you for the tutorial. I am using this to remove the database dump taken yesterday, immediately after creation of latest dump. The shell used in this as below –
    ———————————————————
    sysdate=`date +%Y%m%d%H%M`

    mysqldump nwsm> /usr1/database_backups/nwsm_bckup/nwsm_$sysdate

    prbckup=$(date –date=”-1 day” +”%Y%m%d”2350)

    rm /usr1/database_backups/nwsm_bckup/nwsm_$prbckup
    ———————————————————

    Thanks again. It helped a lot. 🙂

  25. thanks for your clean example of date use for linux. i get your samples
    axsomedate=$(date --date="1 day ago" +"%Y-%m-%d") more elegant of what i used before using:
    axsomedateold=`date +'%Y-%m-%d' -d "1 day ago"`;
    thanks for your time posting good web examples!

  26. How do you get the last DOW of a month? or like the third DOW of a month?
    eg.
    date -d ‘last sunday’ gives you the date of the previous sunday, not the last sunday of the calendar month.
    date -d’second sunday’ gives you the next sunday relative to the current date.
    So today, Friday March 4th, you get the following output:

    -bash-4.1$ date -d ‘first sunday’
    Sun Mar 6 00:00:00 EST 2016
    -bash-4.1$ date -d ‘second sunday’
    Sun Mar 6 00:00:01 EST 2016
    -bash-4.1$ date -d ‘third sunday’
    Sun Mar 20 00:00:00 EDT 2016

Leave a Comment