简体   繁体   中英

java get last day in next month

I have variable nowDate type of Date and I want set variable nextDate contains last day in next month.

For example: nowDate = 2013-04-16

So nextDate will contains 2013-05-31

How can I do that?

Similar to Xavi but one less line of code :-)

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));

Try

private static Date getNextDate(Date nowDate) {
    Calendar c = Calendar.getInstance();
    c.setTime(nowDate);
    c.add(Calendar.MONTH, 1);
    c.set(Calendar.DATE, c.getMaximum(Calendar.DATE));
    Date nextDate = c.getTime();
    return nextDate;
}

Usage:

    Date nowDate = new Date();
    Date nextDate = getNextDate(nowDate);

You could try setting a Calendar to day one two months ahead, and then substract one day:

Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 2);
c.set(Calendar.DAY_OF_MONTH, 1);
c.add(Calendar.DATE, -1);
Date nextDate = c.getTime();

As others have already pointed out, you could also just add one month, and use Calendar.getActualMaximum() to set the last day of the following month.

Calendar c = Calendar.getInstance();
c.add(Calendar.MONTH, 1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
Date nextDate = c.getTime();

Using joda and cribbing off sinarf :

DateTime dt = new DateTime().plusMonths(1);
DateTime lastJoda = dt.dayOfMonth().withMaximumValue();
Date last = lastJoda.toDate();
System.out.println(last.toString());

One way is to increment 2 months to your current month and set the date as 1st. After that decrement the date by 1 and it will give you the last day of month. This will automatically take care of leap year, 30 days, 31 days, 29 days and 28 days months. Program below

public class LastDayofNextMonth {

    public static void main(String args[])
    {

        Calendar cal = Calendar.getInstance();
        cal.set(2013,Calendar.APRIL, 14) ;
        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+2);
        cal.set(Calendar.DATE,1);
        cal.add(Calendar.DATE,-1);
        System.out.println(cal.getTime().toString());

    }
}

tl;dr

Very easy.

YearMonth.now()            // Get entire month for the date current in the JVM’s current default time zone. Better to pass explicitly your desired/expected time zone.
         .plusMonths( 1 )  // Move to the following month.
         .atEndOfMonth()   // Returns a `LocalDate` object, for a date-only value without time-of-day and without time zone.
         .toString()       // Generate a String in standard ISO 8601 format.

2018-02-28

java.time

The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.

Get the date.

LocalDate today = LocalDate.now();

Better to pass explicitly the desired/expected time zone.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ) ;

Pull the YearMonth from that, to represent the month as a whole.

YearMonth ym = YearMonth.from( today ) ;

Or skip the LocalDate entirely.

YearMonth ym = YearMonth.now( ZoneId.of( "America/Montreal" ) ) ;

Move to next month.

YearMonth ymNext = ym.plusMonths( 1 ) ;

Get the date at end of the month.

LocalDate ld = ymNext.atEndOfMonth() ;

Generate a String in standard ISO 8601 format: YYYY-MM-DD.

String output = ld.toString() ;

For other formats, search Stack Overflow for DateTimeFormatter class.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , Calendar , & SimpleDateFormat .

The Joda-Time project, now in maintenance mode , advises migration to the java.time classes.

To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 .

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .

Use Calendar :

First Set the Calendar to the next month. Use: cal.add(Calendar.MONTH, 1);

Then Use getActualMaximum to calculate the last day of the month that you set in previous step.

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

public class Main{

    public static void main(String ar[]){
        Calendar cal = Calendar.getInstance();

        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        cal.add(Calendar.MONTH, 1);
        Date lastDateOfNextMonth = cal.getTime();
        System.out.println(lastDateOfNextMonth ); 

    }
}

IDEONE DEMO

we have so many good answers, however all above answers have code like:

cal.add(Calendar.MONTH, 1);

this code produce a little confusion because Months start at 0, so 1 is for February.

(Edit: The integer in the add() function is not the month number (1=february) but the number of months to add )

You can do the following to get last day of month

Calendar calendar = Calendar.getInstance();   
calendar.setTime(date);   
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM