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

吃可爱长大的小学妹 提交于 2021-02-04 18:40:09

问题


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.


回答1:


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.




回答2:


date can parse the date on the command line like so:

date -j -f %s 1380628152

which is the date+time in seconds since the UNIX epoch. You can combine the command abovewith your command. The -j means you don't want to actually set the date. The -f specifies a strftime string to use to parse the date on the command line.

Please note that this is on a BSD system and it looks like you are on a GNU system with different options to date (but it must support something similar).



来源:https://stackoverflow.com/questions/19112772/get-monday-and-sunday-etc-for-a-week-for-any-date-as-parameter-in-unix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!