faszynski
faszynski

Reputation: 439

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?

Upvotes: 5

Views: 15412

Answers (9)

Basil Bourque
Basil Bourque

Reputation: 338604

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.

Upvotes: 3

Eng. Samer T
Eng. Samer T

Reputation: 6526

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 )

Upvotes: 0

Xavi López
Xavi López

Reputation: 27880

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();

Upvotes: 4

Ritesh Kumar Gupta
Ritesh Kumar Gupta

Reputation: 5191

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

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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);

Upvotes: 6

Joe2013
Joe2013

Reputation: 997

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());

    }
}

Upvotes: 1

Jaydeep Rajput
Jaydeep Rajput

Reputation: 3673

You can do the following to get last day of month

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

Upvotes: -1

jgreen
jgreen

Reputation: 1160

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));

Upvotes: 6

hd1
hd1

Reputation: 34657

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());

Upvotes: 1

Related Questions