Sunday, 6 March 2022

Java: Get start time of next month date

Below snippet return the start of next month date.

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

	calendar.set(Calendar.DATE, 1);
	calendar.set(Calendar.HOUR_OF_DAY, 0);
	calendar.set(Calendar.MINUTE, 0);
	calendar.set(Calendar.SECOND, 0);
	calendar.set(Calendar.MILLISECOND, 0);
	calendar.add(Calendar.MONTH, 1);
	
	return calendar.getTime().getTime();
}

Find the below working application.

 

GetStartOfNextMonth.java

package com.sample.app.time;

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

public class GetStartOfNextMonth {

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

		calendar.set(Calendar.DATE, 1);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.add(Calendar.MONTH, 1);
		
		return calendar.getTime().getTime();
	}

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

		long startOfNextMonth = startOfNextMonth(today.getTime());

		Date startOfNextMonthDate = new Date(startOfNextMonth);

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

	}

}

Output

today : Sat Feb 26 09:38:25 IST 2022
startOfNextMonthDate : Tue Mar 01 00:00:00 IST 2022



    


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment