Java Program to return a Date set to the last possible millisecond of the minute

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, second and milliseconds.

For seconds −

calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));

For milliseconds −

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 minute −

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();
      // seconds
      calendar.set(Calendar.SECOND, calendar.getMaximum(Calendar.SECOND));
      // milliseconds
      calendar.set(Calendar.MILLISECOND, calendar.getMaximum(Calendar.MILLISECOND));
      System.out.println(calendar.getTime());
   }
}

Output

Fri Nov 23 07:17:59 UTC 2018
raja
Published on 21-Dec-2018 11:25:01
Advertisements