The following code enables you to find the first and last day of a month in your JAVA code.
package others;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateTest {
/**
* @param args
*/
public static void main(String[] args) {
Date dt = null;
// Get the last day of Feb. 2012
dt = lastDayOfMonth(2012, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
// Format the current date object with this formatter.
String date = sdf.format(dt);
System.out.println(date);
dt = firstDayOfMonth(2012, 1);
sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
date = sdf.format(dt);
System.out.println(date);
}
public static Date lastDayOfMonth(int year, int month){
// Get an instance of current Calendar
Calendar ct = Calendar.getInstance();
// Set the year to be the supplied year.
ct.set(Calendar.YEAR, year);
// Set the month to be a month ahead than the
// supplied month
// This is done because setting DAY_OF_MONTH to 0
// gives the last day of previous month
ct.set(Calendar.MONTH, month + 1);
// To get the last day of current supplied month
// Set the DAY_OF_MONTH to 0 for the next month
ct.set(Calendar.DAY_OF_MONTH, 0);
// Return the current Date object
return ct.getTime();
}
public static Date firstDayOfMonth(int year, int month){
// Get an instance of current Calendar
Calendar ct = Calendar.getInstance();
// Set the year to be the supplied year.
ct.set(Calendar.YEAR, year);
// Set the month to be the supplied month
ct.set(Calendar.MONTH, month);
// To get the first day of current supplied month
// Set the last day of month to 1
ct.set(Calendar.DAY_OF_MONTH, 1);
// Return the current Date object
return ct.getTime();
}
}