Linux – How to get relative date based on relative date by linux date command

datelinux

Can I get "last monday based on 10 minutes ago" by linux date command ?

For example

  • current time: 2016-02-09 00:05:00
  • expected result: 2016-02-01 00:00:00

Best Answer

If you have faketime and your date is dynamically linked:

faketime -f -10m date -d 'last monday' '+%F %T'

With ksh93 (only builtin commands):

printf '%(%F %T)T\n' "$(printf '%(%Y.%m.%d)T' '10 minutes ago')-0 last monday"

Here, if it was last Sunday instead of last Monday, you could do:

date -d "$(date -d '10 minutes ago' +"%F -%u day")"

Or if it was last Saturday:

date -d "$(date -d '10 minutes ago' +"%F -%w day -1 day")"

But for last Monday or any other day of the week, it involves a bit of arithmetic:

eval "date -d \"$(date -d '10 minutes ago' +'%F -$(((%u+5)%%7+1)) day')\""

Otherwise, you can always do:

d=$(date -d 'last monday'); sleep 600; printf '%s\n' "$d"

;-)

Related Question