(OLDER) <- More Stuff -> (NEWER) (NEWEST)
Printer Friendly Version



Best of CUSM: yesterdays date


What is this stuff?

If this isn't exactly what you wanted, please try our Search (there's a LOT of techy and non-techy stuff here about Linux, Unix, Mac OS X and just computers in general!):



References: <d1c185ef.0201230019.4a838487@posting.google.com>

<941yfzy2hy.fsf@foo-bar-baz.cc.vt.edu>

Before you jump down to the comments and post a Gnu date solution (or anything else), please READ the rest of the article AND the comments. Doing so will help prevent you looking like a fool and will save me the time necessary to point out that you didn't bother to read before posting something we already know..

Finding yesterday's date is easy in languages like Perl:


# this example is programmed for clarity, not efficiency
$rightnow=time();
$rightnow -= (24 * 60 * 60);
print scalar localtime($rightnow);

But in the shell (without Gnu date) it can be harder. You'll see people recommend something like:

#!/bin/ksh
yesterday=$(TZ=EST26EDT date +%mm-%d-%yy)  

where the timezone is selected for the proper effect, but that isn't actually going to work always.

Tapani Tarvainen posted a better solution:

#! /usr/bin/ksh
# Get yesterday's date in YYYY-MM-DD format.
# With argument N in range 1..28 gets date N days before.
# Tapani Tarvainen January 2002
# This code is in the public domain.

OFFSET=${1:-1}

case $OFFSET in
  *[!0-9]* | ???* | 3? | 29) print -u2 "Invalid input" ; exit 1;;
esac

eval `date "+day=%d; month=%m; year=%Y`
typeset -Z2 day month
typeset -Z4 year

# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=$((day - OFFSET))
if (( day <= 0 )) ;then
  month=$((month - 1))
  if (( month == 0 )) ;then
    year=$((year - 1))
    month=12
  fi
  set -A days `cal $month $year`
  xday=${days[$(( ${#days[*]}-1 ))]}
  day=$((xday + day))
fi

print $year-$month-$day
print $month/$day/${year#??}

You may also want to look at http://aplawrence.com/SCOFAQ/FAQ_scotec6datemath.html and http://aplawrence.com/Unix/yesterday.html




Click here to add your comments

---July 13, 2004

The following command will do the job without any mess.

$ date --date='1 day ago'


- amber

---July 13, 2004


Thanks Amber!

It's only true on Linux, but that does point out the importance of reading "info date" instead of just "man date" - you won't find that option spelled out fully in the man page, but the info doc does explain it.

--
TonyLawrence




---August 4, 2004

The script doesn't work.
When day becomes smaller then -9, then, by the typesetting of -Z2, day == 10. While 10 !<=0, you'll get a date you've never expected.

Norbert Groen

---August 25, 2004

need any formated string? and like perl. so take:

$|=1; # flush output

$rightnow=time() - (24 * 60 * 60);

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime
($rightnow);
$mon +=1; # always that

$mon = '0' . $mon if ( length $mon < 2 );

$mday = '0' . $mday if ( length $mday < 2 );

$yesterday = ( $year + 1900 ) . '.' . $mon . '.' . $mday;

print $yesterday . "\n";

exit 0;





---December 8, 2004

echo $(date --date='1 day ago' +%Y%m%d)

worked fine on linux, thankx "Amber"

-merouane


---December 13, 2004

here the script of tapani in pure bash

#!/bin/bash

OFFSET=1;

eval `date "+day=%d; month=%m; year=%Y"`

# Subtract offset from day, if it goes below one use 'cal'

# to determine the number of days in the previous month.

day=`expr $day - $OFFSET`

if [ $day -le 0 ] ;then

month=`expr $month - 1`

if [ $month -eq 0 ] ;then

year=`expr $year - 1`

month=12

fi

set `cal $month $year`

xday=${$#}

day=`expr $xday + $day`

fi

echo $year-$month-$day


P.s.= i'm sorry but this editing loss indentation

--
stetor





---December 13, 2004



---December 28, 2004

Hi,
My problem is that i want to compute a date (before or after) based on a fixed date.
For example my shell parameter is : D='12/25/2004'
and i want to obtain D-5, D+2, D+4, D+5
Before starting to write a complex shell script, i want to be sure that i cannot use the date command. Any ideas ?

Thanks
Chris





Wed Mar 16 20:44:49 2005: Subject:   TonyLawrence

gravatar
Robert Wolf sent email as follows:

Your script on your web page, has a bug in it, below is the corrected version. For example when you set N to a large value like 25 or 26 or 27 or 28 then depending on the current day of the month, the variable 'day' will be more than 2 digits, i.e. -10 say. Now the value '-10' will not fit in a 'typeset -Z2' variable, it needs to be 'typeset -Z3'.

#!/bin/ksh
# Get yesterday's date in YYYY-MM-DD format.
# With argument N in range 1..28 gets date N days before.
# Tapani Tarvainen January 2002
# This code is in the public domain.

OFFSET=${1:-1}

case $OFFSET in
*[!0-9]* | ???* | 3? | 29) print -u2 "Invalid input" ; exit 1;;
esac

eval `date "+day=%d; month=%m; year=%Y`
typeset -Z3 day month
typeset -Z4 year

# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=$((day - OFFSET))
if (( day <= 0 )) ;then
month=$((month - 1))
if (( month == 0 )) ;then
year=$((year - 1))
month=12
fi
set -A days `cal $month $year`
xday=${days[$(( ${#days[*]}-1 ))]}
day=$((xday + day))
fi

typeset -Z2 day month
print $year-$month-$day
print $month/$day/${year#??}




Tue Jun 7 15:43:38 2005: Subject:   anonymous


"date --date=yesterday" or "date -d yesterday" works with 'gnu date', not only on linux.
"date --version" will tell you, if your system uses 'gnu date':

save-lin:/ # date --version
date (coreutils) 5.2.1
Written by David MacKenzie.

Copyright (C) 2004 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

-thomas



Mon Aug 14 14:43:00 2006: Subject:   anonymous


If you don't have gnu date, the tip at:

http://aplawrence.com/SCOFAQ/FAQ_scotec6datemath.html

is more elegant....

bil




Thu Feb 22 20:22:36 2007: Subject:   anonymous


Screw all that calculation crap. Here is a one-liner to provide yesterday's date in a shell variable.

YEST=`TZ="GMT+24" date +'%Y%m%d'`

that will provide yesterday in CCYYMMDD format. Don't like that format?
Change it by consulting strftime on your system.



Fri Feb 23 15:13:54 2007: Subject:   BigDumbDinosaur


Screw all that calculation crap. Here is a one-liner to provide yesterday's date in a shell variable.

YEST=`TZ="GMT+24" date +'%Y%m%d'`

that will provide yesterday in CCYYMMDD format. Don't like that format? Change it by consulting strftime on your system.


You can rearrange the date parameters to produce a different format. For example:
YEST=`TZ="GMT+24" date +'%m/%d/%Y'`
will produce a MM/DD/YYYY format.

If you need to go back more than a day just increment the GMT parameter by 24 per day. For example:
YEST=`TZ="GMT+72" date +'%m/%d/%Y'`
gives you the date of three days ago. To go forward, make the GMT parameter negative, e.g.:
YEST=`TZ="GMT-24" date +'%m/%d/%Y'`
gives you the date of the next day. You could also write that as:
YEST=`TZ="GMT-$((24*ND))" date +'%m/%d/%Y'`
with KSH or BASH, where ND is the number of days. The maximum range for ND is +/- 365 days.



Fri Feb 23 17:32:33 2007: Subject:   TonyLawrence

gravatar
Sigh..

The TZ method was mentioned in the article body and as pointed out there and in the News articles referenced, IT WON'T ALWAYS WORK.





Fri Feb 23 18:43:19 2007: Subject:   BigDumbDinosaur


The TZ method was mentioned in the article body and as pointed out there and in the News articles referenced, IT WON'T ALWAYS WORK.

I wasn't reinventiing the wheel and I didn't say that it was 100 percent reliable. <Smile> I was merely pointing out how that method could be extended with a little twiddling.

For my applications, I use a small C program that reads STDIN for a date in YYYYMMDD format, converts it to a SQL date number, adds X number of days (which if negative, goes back in time), converts the result back to YYYYMMDD format and writes that on STDOUT. It's trustworthy from October 1752 (the first full month after the British empire adopted the Gregorian calendar) to December 31, 9999.






Tue May 1 12:24:04 2007: Subject: www.iphone2die4.com   anonymous


errr.... how about:

yday=$(date --date "1 day ago")



Tue May 1 12:26:04 2007: Subject:   TonyLawrence

gravatar
How about you actually READ everything written?



Sun Nov 30 19:00:45 2008: Subject:   anonymous


Great solution! Never knew of that option but now that I do it makes things alot easier.



Fri Jun 5 05:58:02 2009: Subject:   anonymous

gravatar
I see why the simpler shell solution doesn't always work. However the improved version is more complicated than I need it.
This is sufficient for my purpose (machine uses UTC):
#!/bin/bash
typeset -i H
H=$(date '+%H')+1
TZ=UTC$H date '+%Y%m%d'




Fri Jun 5 10:31:20 2009: Subject:   TonyLawrence

gravatar
Nothing wrong with that. It's important to realize the potential issues, but if they don't apply to you, go for it.



Mon Jun 8 20:29:16 2009: Subject: I have had a few run-ins with this issue myself.   snoopy

gravatar
Just my two cents, but the TZ really does not work too well. I have used this in my code/scripts for the past two years and found some strange behavior. It used to run on Solaris 8 fine, I think, but now we are on Solaris 10 and anything beyond 6 days causes it to fail. I am not sure if this was failing before or not.


For example:

date
Mon Jun 8 20:22:55 GMT 2009

YEST=`TZ="GMT+72" date +'%m/%d/%Y'`
echo $YEST
06/05/2009

YEST=`TZ="GMT+144" date +'%m/%d/%Y'`
echo $YEST
06/02/2009

YEST=`TZ="GMT+168" date +'%m/%d/%Y'`
echo $YEST
06/08/2009

-- After 144 hours the thing is AFU.


I tried to do this in Perl instead: Name the following as ydate.pl, and run with the argument as the amount to subtract. ./ydate.pl 8 I incorporate it as a subroutine to calculate date. Or you can use it as is and use bash or korn to make an external call to calculate.

#!/usr/bin/perl

$var1 = $ARGV[0];

sub ydate {

my $var=shift;

$subtract = ($var * 24 * 60 * 60); # Calculate the number of seconds in a day, $var is a day multiplier.

($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime( (time() -($subtract))); # Get time

$year += 1900; # Add amount of years to add to current year, necessary for Perl.
$mon += 1; # Add 1 to month of year variable, localtime month is "0" based.
$mon = sprintf("%02d", $mon ); # Add 2 decimal places, necessary if mon is 1-9.
$mday = sprintf("%02d", $mday ); # Add 2 decimal places, necessary if mday is 1-9.

return "${year}${mon}${mday}";

}

print "DATE: " . (&ydate($var1)) . "\n";

Hope it helps.



Wed Aug 19 08:56:25 2009: Subject:   archanamangamuri

gravatar
#!/usr/bin/perl

my $yesterday=`date -d 'yesterday' +%Y%m%d`;
chomp($yesterday);
print"date $yesterday\n";


ad





Wed Aug 19 10:50:34 2009: Subject:   TonyLawrence

gravatar
Wow!

Useless use of Perl award, pointless use of "chomp", plus extra points for not reading, and more points for being Linux specific.





Don't miss responses! Subscribe to Comments by RSS or by Email

Click here to add your comments


If you want a picture to show with your comment, go get a Gravatar



/Bofcusm/1455.html copyright 1997-2004 (various authors) All Rights Reserved

Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more. We appreciate comments and article submissions.

Publishing your articles here

Jump to Comments



Many of the products and books I review are things I purchased for my own use. Some were given to me specifically for the purpose of reviewing them. I resell or can earn commissions from the sale of some of these items. Links within these pages may be affiliate links that pay me for referring you to them. That's mostly insignificant amounts of money; whenever it is not I have made my relationship plain. I also may own stock in companies mentioned here. If you have any question, please do feel free to contact me.

Specific links that take you to pages that allow you to purchase the item I reviewed are very likely to pay me a commission. Many of the books I review were given to me by the publishers specifically for the purpose of writing a review. These gifts and referral fees do not affect my opinions; I often give bad reviews anyway.

We use Google third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.



More:
       - OSR5
       - Bofcusm


Unix/Linux Consultants

Skills Tests

Guest Post Here








card_image






My Favorites

Change Congress