Any custom script available to work out the last date of the previous month?

Anyone here has a custom script to work out the last date of the previous month? As in the calendar, the last date of the month can be either 31 or 30 or 29 or 28.

Thanks

1 Like

Hello @kong_ting_how.

It’s very good question. I can share with you 2 variants of custom script. The first one uses deprecated Java class Calendar. It works, but it’s not recommended to use in new Java versions. The second one requires import of java.time libraries. Please see scripts below.

@CustomScriptAction(
   output = 'last_date'
)

def customScript() {

            def calendar = Calendar.getInstance();            
            def year = calendar.get(Calendar.YEAR);
            def month = calendar.get(Calendar.MONTH);     
            def date = calendar.get(Calendar.DAY_OF_MONTH);
            def timezone = calendar.getTimeZone().getID();
            calendar.set(year, month-1, date); 
            def maxday = calendar.getActualMaximum(calendar.DAY_OF_MONTH);
            def last_date = RDateTime.of(year,month,maxday,0,0,0,timezone);            
}

The second script:

import java.time.*

@CustomScriptAction(
   output = 'last_date2'
)

def customScript() {

        ZonedDateTime zonedDateTime = RDateTime.now().asZonedDateTime();
        boolean isLeapYear = Year.isLeap(zonedDateTime.getYear());
        RDateTime.of(zonedDateTime.withDayOfMonth(ZonedDateTime.now().minusMonths(1).getMonth().length(isLeapYear)));            
}

Hope that helps :slight_smile:

3 Likes

Thanks Lera. I will give it a try and let you know the outcome.

2 Likes