When trying to get last date of next month getting last date of next month of next year in java

116 views Asked by At

Trying to run this code it was working perfectly fine till OCT but in NOV it is like firstdate 2019-12-01 & lastdate 2020-12-31

public class Test1 {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();         
        calendar.add(Calendar.MONTH, 1);
        String date;    
        calendar.set(Calendar.DATE,calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        Date nextMonthFirstDay = calendar.getTime();
        date=new SimpleDateFormat("YYYY-MM-dd").format(nextMonthFirstDay).toLowerCase();
        System.out.println("firstdate "+ date);

        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        Date nextMonthLastDay = calendar.getTime();
        date=new SimpleDateFormat("YYYY-MM-dd").format(nextMonthLastDay).toLowerCase();
        System.out.println("lastdate  "+date);

    }
}

I don't know why it is showing like this.. Is it a fault or bug in java ?

2

There are 2 answers

0
www.hybriscx.com On

Change your date format to yyyy-MM-dd (notice lowercase for year)

They both represent a year but yyyy represents the calendar year while YYYY represents the year of the week.

So something like...

date=new SimpleDateFormat("yyyy-MM-dd").format(nextMonthLastDay).toLowerCase();

Hope it helps!

3
deHaar On

You seem to already have got an answer that works, however, here is one that uses the modern datetime API java.time and is s little more readable than the way you are calculating the first and last day of the next month based on today:

public static void main(String[] args) {
    // base is today
    LocalDate today = LocalDate.now();
    /*
     * create a LocalDate from 
     * - the year of next month (may be different)
     * - the current month plus 1 and 
     * - the first day
     * ——> first day of next month
     */
    LocalDate firstDayOfNextMonth = LocalDate.of(
            today.plusMonths(1).getYear(),
            today.getMonth().plus(1),
            1);
    /*
     * create a LocalDate from 
     * - the first day of next month (just created above)
     * - add a month and
     * - subtract one day
     * ——> last day of next month
     */
    LocalDate lastDayOfNextMonth = firstDayOfNextMonth.plusMonths(1).minusDays(1);

    // print the results
    System.out.println("first date of upcoming month:\t"
                        + firstDayOfNextMonth.format(DateTimeFormatter.ISO_DATE));
    System.out.println("last date of upcoming month:\t"
                        + lastDayOfNextMonth.format(DateTimeFormatter.ISO_DATE));
}

Don't be misled by the formatting, there are significantly fewer lines of code and their output is

first date of upcoming month:   2019-12-01
last date of upcoming month:    2019-12-31