Signup/Sign In

Java LocalDate minus() Method

Java minus() method is used to minus a field of a date. The field can be a day, month, or a year. This method returns a new date after subtracting the specified field. For example, we have a date 2012/02/10 and want to subtract 2 days from date then the minus method is suitable for that.

It takes two arguments, one is the amount of field and the second is the name of the field. It returns a new LocalDate after subtracting the specified field.

Syntax

public LocalDate minus(long amountToSubtract, TemporalUnit unit)

Parameters:

amountToSubtract - the amount of field to subtract.

unit - the name of the field like: day, month, etc.

Returns:

It returns a new localdate after subtracting.

Time for an Example

Let's take an example to minus two days by using the minus() method. Here, we have mentioned first argument as 2 and the second argument as days. See the below example.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit; 
public class DateDemo {
	
	public static void main(String[] args){  
		
		LocalDate localDate = LocalDate.of(2016, 10, 21);
		System.out.println(localDate);
		localDate = localDate.minus(2,ChronoUnit.DAYS);
		System.out.println("New date : "+localDate);
	}
}


2016-10-21
New date : 2016-10-19

Time for another Example

Let's take another example to understand the use of the minus() method. Here, we are getting a new LocalDate after subtracting 2 months from the date.

import java.time.LocalDate;
import java.time.temporal.ChronoUnit; 
public class DateDemo {
	
	public static void main(String[] args){  
		
		LocalDate localDate = LocalDate.of(2016, 10, 21);
		System.out.println(localDate);
		localDate = localDate.minus(2,ChronoUnit.MONTHS);
		System.out.println("New date : "+localDate);
	}
}


2016-10-21
New date : 2016-08-21

Live Example:

Try with a live example, execute the code instantly with our powerful Online Java Compiler.



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.