August 17 2016

Java calendar last day of month

Java calendar last day of month

Following are the different ways to get last day of the month

  • Set the Calendar object to be in the month for which you need the last date, getActualMaximum(Calendar.DAY_OF_MONTH) will give you the last date of that month.
  • Setting the calendar to the first of next month and subtract a day.

calendar.get(Calendar.DAY_OF_WEEK) returns int values from 1 to 7(1-Sunday and 7-Saturday)

Example


package com.answersz;

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

public class JavaCalendarLastDayOfMonth {

public static void main(String[] args) {

// Java calendar last day of month

// Using getActualMaximum method

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));

Date lastDtOfMonth = cal.getTime();

System.out.println("Last Date of the month : " + lastDtOfMonth);
System.out.println("Last day of the month :"
+ cal.get(Calendar.DAY_OF_WEEK));

// Setting the calendar to the first of next month
// and subtract a day.

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DATE, 1);
calendar.add(Calendar.DATE, -1);

Date lastDt = calendar.getTime();

System.out.println("Last Date of the month : " + lastDt);
System.out.println("Last day of the month :"
+ calendar.get(Calendar.DAY_OF_WEEK));

}

}

Output


Last Date of the month : Wed Aug 31 13:41:22 IST 2016
Last day of the month :4
Last Date of the month : Wed Aug 31 13:41:22 IST 2016
Last day of the month :4


Copyright © 2014. All rights reserved.

Posted August 17, 2016 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*