Tarik
Tarik

Reputation: 159

How to Get next monthyear(YYYYMM) by passing any monthyear(YYYYMM) in Java?

Example, I have a monthyear on String, like this:

202108 

And I want to next month by passing above month in below format:

202109

What is the best way to do this?

Upvotes: 1

Views: 501

Answers (3)

deHaar
deHaar

Reputation: 18578

Java 8+ ⇒ java.time.YearMonth:

public static void main(String[] args) throws Exception {
    // create a formatter for the String format you are using
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
    // use it in order to parse the String to a YearMonth
    YearMonth yearMonth = YearMonth.parse("202108", dtf);
    // add a month to have the next one
    YearMonth nextYearMonth = yearMonth.plusMonths(1);
    // and print it using the formatter
    System.out.println(nextYearMonth.format(dtf));
}

Output:

202109

If you want it as a method/function, then try something like

public static String getYearMonthAfter(String month) {
    // create a formatter for the String format you are using
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuuMM");
    // use it in order to parse the String to a YearMonth
    YearMonth yearMonth = YearMonth.parse(month, dtf);
    // add a month to have the next one
    YearMonth nextYearMonth = yearMonth.plusMonths(1);
    // and return the resulting String by means of the formatter
    return nextYearMonth.format(dtf);
}

Upvotes: 5

yuzk
yuzk

Reputation: 36

SimpleDateFormat and Calendar can help you a lot.

    public static String getNextMonth(String s) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Calendar cal = Calendar.getInstance();
        try{
            cal.setTime(sdf.parse(s));
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
        cal.add(Calendar.MONTH, 1);
        return sdf.format(cal.getTime());
    }

Upvotes: 2

Pranav Choudhary
Pranav Choudhary

Reputation: 2806

You can use add function in Calendar class to add month

public String getNextMonth(String time){

   DateFormat sdf = new SimpleDateFormat("yyyyMM");
   Date dt = sdf.parse(time);
  
   Calendar c = Calendar.getInstance();
   c.setTime(dt);
   c.add(Calendar.MONTH, 1);  //adding a month 

   String req_date = sdf.format(c.getTime());

   return req_date;

}

Upvotes: 1

Related Questions