Tell me more ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How can I use the date command to convert something like "monday week 40" into a ISO date?

I am playing with something like this:

date --date='monday week 40' +'%Y-%m-%d'

And the date I'm searching for would be 2011-10-03.

But my problem is that this date string is not valid, so I need another approach to solve this problem.

/Thanks

share|improve this question
The following link is about what determines on which day of the year a numbered week begins. Week numbering (Wikipedia).. It effectively explains why the 1st of Janunuary of this year is in ISO week 52 .. The %V format sequence used by 'user unknown' reports the ISO week number. – Peter.O Sep 1 '11 at 16:16

2 Answers

up vote 3 down vote accepted

Really ugly and probably works only with GNU date:

date -d "$( date -d "$( date +'%Y-01-01' ) +40 weeks") -$( date -d "$( date +'%Y-01-01' ) +40 weeks" +'%w' ) days+1 day" +'%Y-%m-%d'

Tested only for your 3 October example, may fail for some other cases.


Update: If you have a non eng locale you need to specify the output from the inner date to get to to work. (And %F just is YYYY-MM-DD).

date -d "$(date -d "$(date +'%Y-01-01') +40 weeks" +"%F") -$(date -d "$(date +'%Y-01-01') +40 weeks" +%w) days +1 day" +"%F"
share|improve this answer
1  
You missed to format the output from the inner date so the outer could use it correctly. – Johan Sep 1 '11 at 11:19
@Johan, I had no problem with using the default format. Maybe it is locale specific? I use en_US. Good point anyway. – manatwork Sep 1 '11 at 11:34
For the date I use the Swedish locale, so there is the difference. – Johan Sep 1 '11 at 13:09
Thanks for the locale adjustment. I have a custom date format and had the same problem.. I had almost sorted it out, but now you've posted it I'll use your tweak; it's better. – Peter.O Sep 1 '11 at 14:32

An alternative approach:

date --date "+$((40-$(date +%V)))weeks last monday"  +"%F"
  • 40 is the week you search for
  • date +%V returns the current week (35)
  • 40-35 = 5, which is the number of weeks to add
  • from there, seek the last monday
share|improve this answer
good one, and it works with my custom date setting. – Peter.O Sep 1 '11 at 14:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.