Skip to content

Instantly share code, notes, and snippets.

@azakordonets
Created May 19, 2014 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azakordonets/e3e85ce8cefa865bc675 to your computer and use it in GitHub Desktop.
Save azakordonets/e3e85ce8cefa865bc675 to your computer and use it in GitHub Desktop.
Getting last day of the month
/**
* This method will return as a date string of the last day of the month.
* @param month if 0 then we look for current month
* @param format format in which date should be returned as a string
* @return
*/
public static String getEndOfTheMonth(int month, String format){
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
int lastDay = 0;
//if month is 0 then we consider this as a current month
if (month == 0 ){
lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}else if (month > 0 && month <=12 ){
calendar.set(Calendar.MONTH, month);
lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
Date lastDayOfMonth = calendar.getTime();
return dateFormat.format(lastDayOfMonth);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment