Linux Shell date command pit (date 1 month ago strange phenomenon)

Source: Internet
Author: User

The first and last days of this month:

Echo 'date -- Date "$1" + "% Y-% m-01 "'

 

Year = 'date-d "$1" + "% Y "'
Month = 'date-d "$1" + "% m "'
Last_day = 'cal $ month $ year | xargs | awk '{print $ NF }''

Echo $ year-$ month-$ last_day

 

Calculate the first and last days of the previous month:

#! /Bin/sh
# Obtain the first day of the previous month
Echo 'date -- Date "1 month ago $1" + "% Y-% m-01 "'

 

But problems found during the test:

[Lix @ cq01-crm-lin1rd10..com temp] $ echo 'date -- Date "1 month ago 20130302" + "% Y % m "'
201302

[Lixia@cq01-crm-.com temp] $ echo 'date -- Date "1 month ago 20130330" + "% Y % m "'

201303

[Lixia1@cq01-crm-.com temp] $ echo 'date -- Date "1 month ago 20130329" + "% Y % m "'

201303
[Li@cq01-crm-lin1rd10.com temp] $ echo 'date -- Date "1 month ago 20130229" + "% Y % m "'

201301

 

Why is this strange phenomenon? Because the 1 month ago of 20130330 should be 20130230? However, if there is no 30 on January 1, February, it will automatically change to 20130301. Then, % Y % m will get 201301.

 

There is another solution: Get the first day of the month, and then subtract one day, that is, get the last day of the previous month. Set the last value to 01 to get the first day of the previous month.

You can also obtain the first day of the month and the first day of the previous month.

 

Refer:

Http://blog.csdn.net/yifanernei/article/details/5112232

Http://www.cnblogs.com/billyxp/archive/2013/01/31/2886733.html

 

Related Article

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.