Java Data Type How to - Get last day of the month in given string date








Question

We would like to know how to get last day of the month in given string date.

Answer

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/*  w w w .  j  a va2  s  . co m*/
public class Main {

  public static void main(String[] args) {

    Date today = new Date();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(today);

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

    Date lastDayOfMonth = calendar.getTime();

    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println("Today            : " + sdf.format(today));
    System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
  }

}

The code above generates the following result.