Groovy web console

subscribe to the feed Subscribe
to this
site

get yyyyMM from last calendar month

Published 3 months ago by Brett
Actions Execute script  ▶ Edit in console Back to console Show/hide line numbers View recent scripts
//imports
import java.text.SimpleDateFormat;

//run the helper fx
println(lastMonthPeriod());


def lastMonthPeriod(){
    //helper fx to calculate the period of last calendar month
    def cal = Calendar.instance;
    def curYear = cal.get(Calendar.YEAR);
    def curMonth = cal.get(Calendar.MONTH);
 
    if ( curMonth == 0 ) {
        cal.set(curYear-1, 11, 1);
    } else {
        cal.set(curYear, (curMonth-1), 1);
    }
 
    Date periodDate = cal.time;
    SimpleDateFormat fmt = new SimpleDateFormat('yyyyMM');
    String periodString = fmt.format(periodDate);

    return periodString;
}