Sunday 6 March 2022

java: Get start time of next day

Below snippet return the start of next day.

public static long startOfNextDay(long now) {
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(new Date(now));

	calendar.add(Calendar.DAY_OF_MONTH, 1);
	calendar.set(Calendar.MILLISECOND, 0);
	calendar.set(Calendar.SECOND, 0);
	calendar.set(Calendar.MINUTE, 0);
	calendar.set(Calendar.HOUR_OF_DAY, 0);

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

 

Find the below working application.

 

GetStartOfNextDay.java

 

package com.sample.app.time;

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

public class GetStartOfNextDay {
	public static long startOfNextDay(long now) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(now));

		calendar.add(Calendar.DAY_OF_MONTH, 1);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.HOUR_OF_DAY, 0);

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

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

		long startOfNextDayInMillis = startOfNextDay(today.getTime());

		Date startOfNextDay = new Date(startOfNextDayInMillis);

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

	}

}

 

Output

today : Sat Feb 26 10:07:23 IST 2022
startOfNextDay : Sun Feb 27 00:00:00 IST 2022

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment