Java Program to return a Date set to the first possible millisecond of the day after midnight

Java 8Object Oriented ProgrammingProgramming

Let us first set the calendar object.

Calendar calendar = Calendar.getInstance();

Use the getMinimum() method in Java to return the minimum 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.getMinimum(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, calendar.getMinimum(Calendar.MINUTE));

For second and milliseconds.

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

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

Output

Fri Nov 23 00:00:00 UTC 2018
raja
Published on 10-Dec-2018 11:56:56
Advertisements