Perl Gets the end of any month before and after

Source: Internet
Author: User

In BI report development, often need to calculate the year-end, need to use the month-end date, with the date function of the database system needs to be in each place to use the date to write the function, in some special cases, the function will be very complex, even can not achieve the desired results.

For example, in Teradata, the Addmonths function calculates only the month:

Date Increment value Results
2015/01/01 1 2015/02/01
2015/01/31 1 2015/02/28
2015/02/28 -1 2015/01/28
2015/03/31 -1 2015/02/28
2015/02/28 0 2015/02/28

As the table shows, at the end of the month, you can not count the entire month of information, often not the desired results.

It is therefore necessary to add variables to the job to achieve monthly data at the end of the month.

Perl implementation is as follows, simple test, production environment before the launch, please use sprintf format.

#!/usr/bin/perl# Get month End Date # liangwl# 2015/9/18Subadd_delta_month{my($date,$cnt) =@_; my$year=int($date/10000); my$month=int($date/ -)% -+$cnt-1; my$yyyymm= ($year+ Floor ($month/ A)) * -+$month% A+1; my@mmdd; Push@mmdd, QW (0131),(int($yyyymm/ -)%4==0?"0229":"0228"), QW (033104300531 0630073108310930103111301231); returnint($yyyymm/ -).$MMDD[($yyyymm% --1)% A];} Subfloor{my($i) =@_; return$i>=int($i) ?int($i) :int($i) -1;} PrintAdd_delta_month (20150131,- -)."\ n";PrintAdd_delta_month (20150131,- -)."\ n";PrintAdd_delta_month (20150131,- A)."\ n";PrintAdd_delta_month (20150131,0)."\ n";PrintAdd_delta_month (20150131,1)."\ n";PrintAdd_delta_month (20150131, One)."\ n";PrintAdd_delta_month (20150131, A)."\ n";PrintAdd_delta_month (20150131, -)."\ n";

Application scenario: "Last six months statistics", "Change by Chain", "Change year-over", "X quarter YoY" and so on

Perl Gets the end of any month before and after

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.