Java Program to return a Date set to the last possible millisecond of the month before midnight

Java 8Object Oriented ProgrammingProgramming

Use the getMaximum() method in Java to returns the maximum value for the given calendar field. We will use it to set the minute, second and millisecond.

Let us first declare a calendar object −

Calendar dateNoon = Calendar.getInstance();

Now, we will set the hour, minute, second and millisecond to the last possible millisecond on the month before midnight.

// hour, minute and second
calendar.set(Calendar.HOUR_OF_DAY, calendar.getMaximum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calendar.getMaximum(Calendar.MINUTE));
calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));
// millisecond
calendar.set(Calendar.MILLISECOND, calendar.getMaximum(Calendar.MILLISECOND));

Now, do the following for month and day of month −

calendar.set(Calendar.DAY_OF_MONTH, 1); // first day of month
calendar.add(Calendar.MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);

The following is an example to return a Date set to the last possible millisecond of the month before midnight −

Example

 Live Demo

import java.util.Calendar;
import java.util.GregorianCalendar;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Calendar calendar = Calendar.getInstance();
      // hour, minute and second
      calendar.set(Calendar.HOUR_OF_DAY, calendar.getMaximum(Calendar.HOUR_OF_DAY));
      calendar.set(Calendar.MINUTE, calendar.getMaximum(Calendar.MINUTE));
      calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));
      // millisecond
      calendar.set(Calendar.MILLISECOND, calendar.getMaximum(Calendar.MILLISECOND));
      calendar.set(Calendar.DAY_OF_MONTH, 1); // first day of month
      calendar.add(Calendar.MONTH, 1);
      calendar.add(Calendar.DAY_OF_MONTH, -1);
      System.out.println(calendar.getTime());
   }
}

Output

Fri Nov 30 23:59:59 UTC 2018
raja
Published on 21-Dec-2018 11:20:02
Advertisements