Javaexercise.com

How To Add Months To Localdatetime In Java?

 

 

package javaexample;
/* 
 *  Code example to add months to localdatetime in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// String  date is given
		String strDate = "2022-03-14T17:28:13.048999208";
		// parse the date into date time
		LocalDateTime date = LocalDateTime.parse(strDate);

		// Displaying date and time
		System.out.println("Date : "+date);

		// Add 2 months to the date
		LocalDateTime newDate = date.plusMonths(2); 

		// Display result
        System.out.println("New Date : "+newDate);
	}
}

Output:

Date : 2022-03-14T17:28:13.048999208
New Date : 2022-05-14T17:28:13.048999208
 

 

public LocalDateTime plusMonths(long months)

Returns a copy of this LocalDateTime with the specified number of months added.

This method adds the specified amount to the months field in three steps:

  1. Add the input months to the month-of-year field
  2. Check if the resulting date would be invalid
  3. Adjust the day-of-month to the last valid day if necessary

For example, 2007-03-31 plus one month would result in the invalid date 2007-04-31. Instead of returning an invalid result, the last valid day of the month, 2007-04-30, is selected instead.

This instance is immutable and unaffected by this method call.

Parameters:

months - the months to add, may be negative

Returns:

a LocalDateTime based on this date-time with the months added, not null

Throws:

DateTimeException - if the result exceeds the supported date range

 

current date

package javaexample;
/* 
 *  Code example to add months to localdatetime in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// current date time 
		LocalDateTime date = LocalDateTime.now(); 

		// Displaying date and time
		System.out.println("Date : "+date);

		// Add 2 months to the date
		LocalDateTime newDate = date.plusMonths(2); 

		// Display result
		System.out.println("New Date : "+newDate);
	}
}

Output:

Date : 2022-03-15T11:45:03.535544634
New Date : 2022-05-15T11:45:03.535544634
 

negative integeres

package javaexample;
/* 
 *  Code example to add months to localdatetime in Java
 */
import java.time.LocalDateTime;
public class JExercise {
	public static void main(String[] args) {		

		// current date time 
		LocalDateTime date = LocalDateTime.now(); 

		// Displaying date and time
		System.out.println("Date : "+date);

		// Add 2 months to the date
		LocalDateTime newDate = date.plusMonths(-2); 

		// Display result
		System.out.println("New Date : "+newDate);
	}
}

Output:

Date : 2022-03-15T11:46:42.674329548
New Date : 2022-01-15T11:46:42.674329548