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

Java 8Object Oriented ProgrammingProgramming

Let us first set the calendar object.

Calendar calendar = Calendar.getInstance();

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

For hour and minute.

calendar.set(Calendar.HOUR_OF_DAY, calendar.getMaximum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calendar.getMaximum(Calendar.MINUTE));

For second and milliseconds.

// second
calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));
// millisecond
calendar.set(Calendar.MILLISECOND, calendar.getMaximum(Calendar.MILLISECOND));

The following is an example that returns a Date set to the last possible millisecond of the day 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 and minute
      calendar.set(Calendar.HOUR_OF_DAY, calendar.getMaximum(Calendar.HOUR_OF_DAY));
      calendar.set(Calendar.MINUTE, calendar.getMaximum(Calendar.MINUTE));
      // second
      calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));
      // millisecond
      calendar.set(Calendar.MILLISECOND, calendar.getMaximum(Calendar.MILLISECOND));
      System.out.println(calendar.getTime());
   }
}

Output

Fri Nov 23 23:59:59 UTC 2018
raja
Published on 10-Dec-2018 16:18:48
Advertisements