tovachanah
tovachanah

Reputation: 11

Date changing from Groovy to String

I have to find the last date of the last month I am using a Groovy Script

I can get the date part ok but now I have to turn it into a String in the form yyyyMMdd.

Code so far (and yes it works)

    import java.util.GregorianCalendar;
    import java.util.Calendar;
    import java.util.Date;

    Calendar aCalendar = Calendar.getInstance();
    // add -1 month to current month
       aCalendar.add(Calendar.MONTH, -1);

    // set actual maximum date of previous month
          aCalendar.set(Calendar.DATE,aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));

    //read it
      lastDateOfPreviousMonth = aCalendar.getTime();

This returns the date in timestamp form 20160229 105925.240

Now I need to extract 20160229 from the timestamp as a string

I've tried just about everything...

Upvotes: 0

Views: 540

Answers (1)

tim_yates
tim_yates

Reputation: 171144

If this is running on Java 8, you can use the new Java Time classes:

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters

String date = LocalDate.now()
                       .minusMonths(1)
                       .with(TemporalAdjusters.lastDayOfMonth())
                       .format(DateTimeFormatter.ofPattern("yyyyMMdd"))

If this is Java 7 or Java 6, you can use Calendar and a bit of Groovy:

String date = Calendar.instance.with {
    add(MONTH, -1)
    set(DAY_OF_MONTH, getActualMaximum(DAY_OF_MONTH))
    time
}.format('yyyyMMdd')

Upvotes: 2

Related Questions