Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the bash date script to return a day of the week relative to a non-current time?

Tags:

date

linux

bash

Using bash date, I can get it to return a day of the week relative to the current time.

date --d='last Sunday' #Returns date of the Sunday before today

I can also get it to return a day relative to some other date

date --d='02/1/2012 -2 days' #Returns date two days before Feb. 1, 2012

but how can I get it to return the day of the week relative to some non-current time? What I want to do is:

date --d='Sunday before 02/1/2012' #Doesn't work! I want Sunday before Feb. 1

If possible, I would even like to be able to chain strings so that I can reference relative days from the new date:

# Should return 2 days before the Sunday before Feb. 1, 2012
date --d='Sunday before 02/1/2012 - 2 days'

Though this chaining is not as important. Is there some way for bash date to return a day based on the relative day of the week?

like image 377
Roman Avatar asked Feb 09 '12 00:02

Roman


People also ask

How do I get the current day in bash?

Sample shell script to display the current date and time #!/bin/bash now="$(date)" printf "Current date and time %s\n" "$now" now="$(date +'%d/%m/%Y')" printf "Current date in dd/mm/yyyy format %s\n" "$now" echo "Starting backup at $now, please wait..." # command to backup scripts goes here # ...


1 Answers

You can use a little day number arithmetic:

base="02/1/2012"
feb1_dayofweek=$( date -d $base +%w )
target_dayofweek=0   # sunday
date -d "$base - $(( (7 + feb1_dayofweek - target_dayofweek) % 7 )) days"

result:

Sun Jan 29 00:00:00 EST 2012
like image 146
glenn jackman Avatar answered Oct 19 '22 11:10

glenn jackman