Sunday, 6 March 2022

Java: Get start time of next minute

Below snippet return the start time of next minute.

public static long getStartOfNextMinute(long now) {
	Calendar calendar = Calendar.getInstance();
	
	calendar.setTime(new Date(now));
	calendar.set(Calendar.MILLISECOND, 0);
	calendar.set(Calendar.SECOND, 0);
	calendar.add(Calendar.MINUTE, 1);
	
	return calendar.getTime().getTime();
}

 

Find the below working application.

 

GetStartOfNextMinute.java

 

package com.sample.app.time;

import java.util.Calendar;
import java.util.Date;

public class GetStartOfNextMinute {
	public static long getStartOfNextMinute(long now) {
		Calendar calendar = Calendar.getInstance();
		
		calendar.setTime(new Date(now));
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.add(Calendar.MINUTE, 1);
		
		return calendar.getTime().getTime();
	}

	public static void main(String args[]) {
		Date today = new Date();

		long startOfNextMinuteInMillis = getStartOfNextMinute(today.getTime());

		Date startOfNextMinute = new Date(startOfNextMinuteInMillis);

		System.out.println("today : " + today);
		System.out.println("startOfNextMinute : " + startOfNextMinute);

	}
}

Output

today : Sat Feb 26 12:12:12 IST 2022
startOfNextMinute : Sat Feb 26 12:13:00 IST 2022

 

 

 



Previous                                                    Next                                                    Home

No comments:

Post a Comment