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


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

Updated on: 26-Jun-2020

66 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements