Java: How to add “n” minutes to Calendar data object?

Last updated
App Shah
Crunchify » Java and J2EE Tutorials » Java: How to add “n” minutes to Calendar data object?
How to add n minutes to Calendar data object?

Very simple way to add “N” minutes to current time in Java.

Java Code:

package crunchify.com.tutorials;

import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @author crunchify.com
 * How to add "n" minutes to Calendar data object?
 */
public class CrunchifyAddNMinToTimeTest {

	private static final String DATE_FORMAT_MM_dd_yyyy_HH_mm_ss = "MM.dd.yyyy:HH.mm.ss";

	public static void main(String[] args) {

		System.out.println("Main Method Start \n");
		addNMinutesToTime(Calendar.getInstance());
		System.out.println("Main Method exit");
	}

	@SuppressWarnings("static-access")
	public static void addNMinutesToTime(Calendar date) {
		SimpleDateFormat crunchifyDateFormat = new SimpleDateFormat(DATE_FORMAT_MM_dd_yyyy_HH_mm_ss);
		int minutesToAdd = 11;

		// getTime() Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").
		System.out.println("Initial Time: " + crunchifyDateFormat.format(date.getTime()));
		Calendar startTime = date;

		// Field number for get and set indicating the minute within the hour.
		// E.g., at 10:04:15.250 PM the MINUTE is 4.
		startTime.add(date.MINUTE, minutesToAdd);
		String newDateString = crunchifyDateFormat.format(startTime.getTime());

		System.out.println("New Time : " + newDateString + "\n");
		// return dateStr;
	}
}

Output:

Main Method Start 

Initial Time: 12.20.2020:00.02.51
New Time : 12.20.2020:00.13.51

Main Method exit

Process finished with exit code 0

Leave a Comment