UNIX date command to get the day before a date

Source: Internet
Author: User

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-

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.