Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Monday and Sunday etc.. for a week for any date as parameter in Unix

How to get the date of Monday and Sunday in a week for a date?

This gives date for 'last' monday:

date -dlast-monday +%Y%m%d

I want to pass a date as parameter to find the Monday and Sunday for that week. Basically, I want to get Sunday and Monday for a week, for ANY date, NOT only for last monday.

like image 533
Mayukh Roy Avatar asked Jan 12 '23 06:01

Mayukh Roy


1 Answers

Try this:

export day=2013-10-01
date -d "$day -$(date -d $day +%w) days"

This will always print the Sunday before the given date (or the date itself).

date -d "$day -$(date -d $day +%u) days"

This will always print the Sunday before the given date (and never the date itself).

For Mondays you need to add + 1 day:

date -d "$day -$(date -d $day +%u) days + 1 day"

You should also consider what Monday or Sunday you want to get (this wasn't quite clear) for which date. This also depends on whether you consider the Sunday the first or the last day of the week.

like image 149
Alfe Avatar answered Jan 19 '23 10:01

Alfe