2

Suppose that today is Thursday, June 30, 2016.

Then date +%Y%m%d is 20160630, date -d'last-thursday' +%Y%m%d is 20160623, and date -d'next-thursday' +%Y%m%d is 20160707.

However, date -d'last-wednesday' +%Y%m%d is 20160629, and date -d'next-wednesday' +%Y%m%d is 20160706.

Is there an inclusive version of {next,last}-*day which would return today's date if today is day?

agc
  • 7,973
  • 2
  • 29
  • 50
cshin9
  • 1,440
  • 5
  • 20
  • 33
  • I'm not aware of alternative forms of `{next|last}-*day` which includes today. It wouldn't really make sense semantically (linguistically). "Next" and "last" in this context would not ever mean today in normal language terms. Why is it needed? Perhaps some context... You could always make a simple custom script to get that result. – lurker Jun 30 '16 at 15:45
  • What about simply check what day of the week is today (`date +%w`). If it's, for example, Thursday and you're looking for the last Thursday, then you're done. – David Ferenczy Rogožan Jun 30 '16 at 15:46

1 Answers1

2

Inclusive next weekday is built in, just use -d"Thursday", (no prefix), and date will return today if today is Thursday, or next Thursday if not.

But date has no inclusive last, so here's an inclusive last weekday kludge function:

ilast() { a=$(date -d'today' "+%A") ; b=$(date -d"$1" "+%A") ; \
         [ $a != $b ] && echo -n "last " ; echo $b ; }

Test, (which also shows ilast's usage):

for d in Sun. Mon. Tue. Wed. Thu. Fri. Sat. ; do \
    echo -n $(ilast $d)" " ; \
    date -d"$(ilast $d)" "+%Y%m%d" ; \
done | column -t

Output:

last      Sunday     20160626
last      Monday     20160627
last      Tuesday    20160628
last      Wednesday  20160629
Thursday  20160630
last      Friday     20160624
last      Saturday   20160625

The function sets $a to today's weekday, and $b to $1's weekday, which would be a different weekday, unless $1 is today's weekday. So if the weekdays $a and $b are not equal, (six days out of seven they'd differ), we prepend "last " to the weekday's long name. If the weekdays $a and $b are equal, don't print "last ", since, (one day out of seven), the default inclusive next already does the desired thing.

agc
  • 7,973
  • 2
  • 29
  • 50