Java Program to return a Date set to the first possible millisecond of the month after 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 milliseconds.

Let us first declare a calendar object −

Calendar dateNoon = Calendar.getInstance();

Now, we will set the hour, minute, second and millisecond to the first possible millisecond of the month after 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));

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

Output

Thu Nov 01 00:00:00 UTC 2018
raja
Published on 21-Dec-2018 11:22:39
Advertisements