Linux date previous date

In a unix shell, how to get yesterday’s date into a variable?

How would i go about getting yesterdays date into a variable? Basically what i’m trying to achieve is to use grep to pull all of yesterday’s lines from a log file, since each line in the log contains the date in «Mon 01/02/2010» format. Thanks a lot

17 Answers 17

dt=$(date --date yesterday "+%a %d/%m/%Y") echo $dt 

+1 for answering the question precisely. Caveat is that the -yesterday flag may not be supported on posters version of unix

This is the best answer among all the others, short, sweet, easy, handy, cool and it proves the story ‘Give a man a fish he is fed for a day, but teach him to fish, he is fed for life’

You can use GNU date command as shown below

Getting Date In the Past

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

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:

If you have Perl available (and your date doesn’t have nice features like yesterday ), you can use:

pax> date Thu Aug 18 19:29:49 XYZ 2010 pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;') pax> echo $dt 17/08/2010 

@Chris: note that this gives you the date 24 hours ago, which is subtly different from yesterday’s date. If your locale has daylight savings time, this will give the wrong date after 23:00 on the first day of winter time.

@Gilles, that’s not a bad point since I’m using locattime. If you’re concerned about it, you can check if the hour is greater than 6pm, just subtract 6 hours. That should hopefully cover it.

If you are on a Mac or BSD or something else without the —date option, you can use:

date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y' 
date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y' 

+1 just for not assuming that every UNIX question is on Linux. Some of us have to work with other styles as well.

@paxdiablo: agreed, but if no specific info is given than I personally assume that the GNU toolkit is an option 😉 The differences between HP-UX , AIX , Solaris and *BSD are simply to great to guess the flavour.

$(( for arithmetic expansion is nice, but not what @bstpierre was talking about. Even inside there, you should really be using $( . ) for the command expansion: $(( $(date +%s) — 86400 )) .

I have shell script in Linux and following code worked for me:

#!/bin/bash yesterday=`TZ=EST+24 date +%Y%m%d` # Yesterday is a variable mkdir $yesterday # creates a directory with YYYYMMDD format 

TZ is time zone, EST+24 gives yesterday’s date for Eastern Standard time (like wise you can use EST-24 for tomorrow’s date) +%Y%m%d is the format for YYYYMMDD.

This is by far the most succinct version that works on AIX for anyone who is searching for such an answer. AIX doesn’t allow for the -r or -d flags but does in fact allow manipulating the time zone like this! You’ve made my day I’ve been trying to figure this out for like two hours, I’m making a date appear as half a year ago and the other ideas weren’t working.

dt=`case "$OSTYPE" in darwin*) date -v-1d "+%s"; ;; *) date -d "1 days ago" "+%s"; esac` echo $dt 

It works on both Linux and OSX.

Читайте также:  Linux terminal tips and tricks

You have atleast 2 options

perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)' 
date --date yesterday "+%a %d/%m/%Y" | read dt echo $

@Chris: I assumed it wouldn’t be a GNU compatible date but since you didn’t specify the Unix variant I simply guessed 😉 With HP-UX your options are a little more limited, date doesn’t have these options so Perl might be the best option.

Not that it matters but you don’t need to add 1900 to the year if you’re then going to %100 the result 🙂

@paxdiablo: fair point, Perl is obviously not one of my strong points 😉 I’ll +1 your answer instead.

Here is a ksh script to calculate the previous date of the first argument, tested on Solaris 10.

#!/bin/ksh sep="" today=$(date '+%Y%m%d') today=$ ty=`echo $today|cut -b1-4` # today year tm=`echo $today|cut -b5-6` # today month td=`echo $today|cut -b7-8` # today day yy=0 # yesterday year ym=0 # yesterday month yd=0 # yesterday day if [ td -gt 1 ]; then # today is not first of month let yy=ty # same year let ym=tm # same month let yd=td-1 # previous day else # today is first of month if [ tm -gt 1 ]; then # today is not first of year let yy=ty # same year let ym=tm-1 # previous month if [ ym -eq 1 -o ym -eq 3 -o ym -eq 5 -o ym -eq 7 -o ym -eq 8 -o ym - eq 10 -o ym -eq 12 ]; then let yd=31 fi if [ ym -eq 4 -o ym -eq 6 -o ym -eq 9 -o ym -eq 11 ]; then let yd=30 fi if [ ym -eq 2 ]; then # shit. :) if [ ty%4 -eq 0 ]; then if [ ty%100 -eq 0 ]; then if [ ty%400 -eq 0 ]; then #echo divisible by 4, by 100, by 400 leap=1 else #echo divisible by 4, by 100, not by 400 leap=0 fi else #echo divisible by 4, not by 100 leap=1 fi else #echo not divisible by 4 leap=0 # not divisible by four fi let yd=28+leap fi else # today is first of year # yesterday was 31-12-yy let yy=ty-1 # previous year let ym=12 let yd=31 fi fi printf "%4d$%02d$%02d\n" $yy $ym $yd 

Tests

bin$ for date in 20110902 20110901 20110812 20110801 20110301 20100301 20080301 21000301 20000301 20000101 ; do yesterday $date; done 20110901 20110831 20110811 20110731 20110228 20100228 20080229 21000228 20000229 19991231 

Источник

n days ago from a given date on command line

For example, given date is ‘2016-12-31’, n is 2, expected output is ‘2016-12-29’.

I survey date command and get n days ago from current date is easy:
date -d «2 days ago» +%Y-%m-%d

I changed the tags from unix to linux, as this expressive -d behavior is a GNU extension, not found in POSIX, BSD, etc.

Despite @pilcrow’s comment, I have provided a BSD answer as well as a way to solve for either GNU or BSD. Also note that GNU does not require the Linux kernel, nor does it always imply a Linux distribution. I’ve added the «gnu» tag and returned the «unix» tag while leaving «linux» in place.

2 Answers 2

Just mention the date you want to extract two days from:

$ date -d "2016-12-31 2 days ago" +%Y-%m-%d 2016-12-29 

Or a bit better grammatically-wise:

$ date -d "2016-12-31 -2 days" +%Y-%m-%d 2016-12-29 

@cheng indeed, it is so powerful! Note it can sometimes work weirdly: date processes first parameter incorrectly if it is not 1.

If you do not have GNU date, perhaps you have BSD date instead. In that case, you can do this:

date -jf %s $(( $(date +%s) - 86400 * 2 )) 

Note that this is not POSIX, nor is it GNU.

Читайте также:  Astra linux шрифты microsoft

This tells BSD date not to change the clock ( -j ) and to take the input as UNIX time (seconds after 1970/01/01 00:00:00 UTC, -f %s ). The time supplied is a mathematical substitution of the current time ( $(date +%s) , using the same format but as output) minus the number of seconds in a day (86400) times two.

I have, in the past, written code that looks for GNU and then fails over to BSD:

# Usage: _epoch2datefmt UNIX_TIME [+FORMAT] if date -d @1484850180 +%s >/dev/null 2>&1 then _epoch2datefmt() < date -d @"$@"; ># GNU else _epoch2datefmt() < date -jf %s "$@"; ># BSD fi 

For this question, we also need to go the other direction. BSD date needs the format too:

# Usage: _date2epoch YYYY-MM-DD [INPUT_FORMAT] if date -d 2017-01-19 +%s >/dev/null 2>&1 then _yyyymmdd2epoch() < date -d "$1" +%s; ># GNU else _yyyymmdd2epoch() < date -jf "$2" "$1" +%s; ># BSD fi 

Here’s how to put those together to get two days before a given date with either GNU or BSD:

_epoch2datefmt $(( $(_date2epoch 2016-12-31 %Y-%m-%d) - 2 * 86400 )) +%Y-%m-%d 

From the inside out, this converts 2016-12-31 to UNIX time, subtracts two days (there are 86400 seconds in a day), then passes the resulting UNIX time (the answer) to be converted back into YYYY-MM-DD format.

If you wanted this all in one function, it could be:

# Usage: _date_helper INPUT_FORMAT DATE [+OUTPUT_FORMAT] if date -d@1484850180 +%s >/dev/null 2>&1 then _date_helper() < local A=; [ "$1" = %s ] && A=@; shift; date -d "$A$@"; >else _date_helper() < date -jf "$@"; >fi 

(I had to be a little tricky to handle inputting the UNIX time (as indicated by the first argument being %s ) since GNU’s date -d requires a leading @ . This saves that prefix in $A if necessary, purges the format (GNU is smart and doesn’t otherwise need it), then passes the rest off to the GNU date command. The BSD version should be self-explanatory.)

Here’s how to run it to get «two days before 2016-12-31» using this function:

_date_helper %s $(( $(_date_helper %Y-%m-%d 2016-12-31 +%s) - 86400 * 2)) +%Y-%m-%d 

Источник

Get the date (a day before current time) in Bash

For the usage on Ubuntu with date function: $(date +%Y:%m:%d -d «1 day ago»), output is: 2013:04:21. And if you want the date 10 days before, you can use $(date +%Y:%m:%d -d «10 days ago») or $(date +%Y:%m:%d -d «10 day ago»)

This bash function will work on both Linux and OSX. Basically it tries the GNU Linux style first. If that fails it tries the OSX style. Call it with an argument of the number of days in the past you want the date. If you pass no argument it assume 0 days. This code is a one-liner, so cut and paste should work — no line endings assumed. date_days_past () < days_past=$<1:-0>; if ! date -v-$d +%Y%m%d 2>/dev/null; then date —date=»-$ day» +%Y%m%d; fi >

If you have BSD (OSX) date you can do it like this:

date -j -v-1d Wed Dec 14 15:34:14 CET 2011 

Or if you want to do date calculations on an arbitrary date:

date -j -v-1d -f "%Y-%m-%d" "2011-09-01" "+%Y-%m-%d" 2011-08-31 

You need to install the GNU version of date , available through the coreutils package, to make this syntax work on macOS. If you’re using Homebrew, you can install it via brew install coreutils , after which you should be able to use GNU date through the gdate command. See: topbug.net/blog/2013/04/14/…

Читайте также:  Exit linux системный вызов

where 1d defines current day minus 1 day. Similarly,

date -v-1w +%F — for previous week date

date -v-1m +%F — for previous month date

IF YOU HAVE GNU DATE,

Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

I find out I can get the previous date with little trick on timezone.

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r` echo $DATE 

This method is not 100% reliable (about 98% actually) if you happen to live in a place using daylight saving time.

Well this is a late answer,but this seems to work!!

 YESTERDAY=`TZ=GMT+24 date +%d-%m-%Y`; echo $YESTERDAY; 

For details about the date format see the man page for date

date=$(date -d "yesterday" '+%Y-%m-%d') echo $date 

That results in date: illegal option: -d on Solaris. Your answer that relies on non-portable GNU extensions to the POSIX-standard date utility for a question about the non-GNU Solaris platform.

perl -e 'print scalar localtime( time - 86400 ) . "\n";' 

Or, use nawk and (ab)use /usr/bin/adb:

/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ ' | adb 

Not very sexy but might do the job:

perl -e 'my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time - 86400);$year += 1900; $mon+= 1; printf ("YESTERDAY: %04d%02d%02d \n", $year, $mon, $mday)' 

Formated from «martin clayton» answer.

You could do a simple calculation, pimped with an regex, if the chosen date format is ‘YYYYMM’:

echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/' 

In January of 2020 it will return 201912 😉 But, it’s only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available 😉

if you are using OSX, but you need create for GNU compatible, install coreutils first

then edit your profile with:

#gnu coreutils first export PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH" 

re-start your terminal, and now you able to use GNU format!

Puts yesterday’s date in YYYY-MM-DD format into variable $yesterday .

#!/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 

Hi medoix, I am not able to find the meaning of $. I know that $# stands for the number of arguments to a script/function. But I am not able to relate to this. Please help.

This doesn’t work for the previus day on change of month . For example today is 1 July , 2013 , the result being printed out is 2013-6-1347 , whereas the expected result is 2013-6-30

Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1 

The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

echo "$(TZ=GMT+30 date +%Y-%m-%d) $(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1 

Источник

Оцените статью
Adblock
detector