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?
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 # ...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With