Sunday 6 March 2022

Java: Get start time of next second

Below snippet return the start time of next second.

public static long getStartOfNextSecond(long now) {
	Calendar calendar = Calendar.getInstance();

	calendar.setTime(new Date(now));
	calendar.set(Calendar.MILLISECOND, 0);
	calendar.add(Calendar.SECOND, 1);

	return calendar.getTime().getTime();
}

 

Find the below working application.

 

GetStartOfNextSecond.java

package com.sample.app.time;

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

public class GetStartOfNextSecond {
	public static long getStartOfNextSecond(long now) {
		Calendar calendar = Calendar.getInstance();

		calendar.setTime(new Date(now));
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.add(Calendar.SECOND, 1);

		return calendar.getTime().getTime();
	}

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

		long startOfNextSecondInMillis = getStartOfNextSecond(today.getTime());

		Date startOfNextSecond = new Date(startOfNextSecondInMillis);

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

	}
}

 

Output

today : Sat Feb 26 12:19:16 IST 2022
startOfNextSecond : Sat Feb 26 12:19:17 IST 2022

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment