The most primitive method is to write a complicated function, know the number of days each month, and handle the leap year situation-this is a bit tedious.
Take a look at the date command and you will find that using it can easily write a very stable function. Date can be specified through-D and then output in the specified format. -D can not only accept the format "1970" or "yesterday", but also the number of seconds since January 1,. Of course, you can also specify the number of seconds for date output. For example:
1[TMN @ zhfx1 zhaoxj] $Date+ %S2 13401815313[TMN @ zhfx1 zhaoxj] $Date-D @ 1340181531 + % Y-% m-%D
4 2012-06-20
In this way, things become very simple. Use the date command to convert the date to seconds, minus 86400 seconds of a day, and then convert it to a normal readable date format. You do not need to consider the complex large and small months and the leap year issues.
Write a function using the above idea: Find the number of Monday in the week of the given date
1 Get_day_monday (){ 2 3 Local datestamp 4 5 Datestamp = $ 1 6 7 # How many seconds from the given date to 1970 8 V_seconds =' Date -D $ {datestamp} + % S' 9 10 # The given date is the day of the week 11 V_week =' Date -D $ {datestamp} + % U' 12 13 # Monday is a few days ago 14 Days_before = $ (v_week- 1 )) 15 16 # How many seconds are there from Monday? 17 Seconds_before = $ (days_before * 86400 )) 18 19 # How many seconds is the distance from Monday to 1970? 20 Monday_seconds = $ (v_seconds- Seconds_before )) 21 22 V_monday =' Date -D @ $ monday_seconds + % Y-% m-% D' 23 24 } 25 26 Get_day_monday2012 - 06 - 20 27 28 Echo $ {V_monday}
Test results:
2012-06-