Is there a mechanism or a method in Joda Time itself/or some other API through which i can achieve the same.??? Please suggest?

Input Date: 2018-04-30

Used Joda Time like this gives output: 2018-05-30

Expected Date : 2018-05-31

Edited Again Want to know if it will be alright to say and do like this meaning

if the input date is the last date(will use the algos shared) then fetch the last date of the next month and

else if input date is anything else then use plusMonths method

right??

String startDate = "2018-04-30";
DateTime startDateTime = new DateTime(startDate, DateTimeZone.UTC);

int repeatEvery = 1;
int numOfPayments = 2;
String endDate = startDateTime.plusMonths(repeatEvery * (numOfPayments-1)).toString();
System.out.println(endDate);

2 Answers

3
AxelH On Best Solutions

Using the Java Time API, it is quite simple to get the last day of a month using a TemporalAdjuster, the API come with some already define, like TemporalAdjusters.lastDayOfMonth().

So here is a simple example on how to get the last day of the next month (based on today).

LocalDate date = LocalDate.now()
    .plus(1, ChronoUnit.MONTHS)
    .with(TemporalAdjusters.lastDayOfMonth()));

This is pretty verbose to be understandable I believe.

To parse the String into a LocalDate. Simply replace now() by parse() like :

LocalDate.parse("2019-05-03", DateTimeFormatter.ISO_DATE);

Using :

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

This is actually already an answer in the duplicate proposed, just need to scoll a bit to find it. It lakes some visibility !!

0
Stefan Wendelmann On

You could do this by the Calendar

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String startDate = "2018-04-30";

    int repeatEvery = 1;
    int numOfPayments = 2;

    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    cal.setTime(sdf.parse(startDate));
    cal.add(Calendar.MONTH, repeatEvery * (numOfPayments - 1));
    System.out.println("intRes: "+sdf.format(cal.getTime()));

    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

    String endDate = sdf.format(cal.getTime());

    System.out.println(endDate);

out:

intRes: 2018-05-30

2018-06-01

I dont know why this is giving me the 2018-06-01 ?