Date and Time

How to Java 8 get current date subtract days LocalDate

Table of Contents

Program

import java.time.LocalDate;

public class DateSubract {
    public static void main(String[] args)
    {
        LocalDate date
            = LocalDate.parse("2021-11-13");
        System.out.println("Date before subtracting : " + date);
        LocalDate returnvalue
            = date.minusDays(7);  
        System.out.println("Date aftersubtracting by 7days: " + returnvalue);
    }
}

Output

Date before subtracting : 2021-11-13
Date aftersubtracting by 7days: 2021-11-06

Description

public static LocalDate parse(CharSequence text)

Obtains an instance of LocalDate from a text string such as 2007-12-03.
The string must represent a valid date and is parsed using DateTimeFormatter.ISO_LOCAL_DATE.

Parameters:

text – the text to parse such as “2007-12-03”, not null
Returns:
the parsed local date, not null

public LocalDate minusDays(long daysToSubtract)

Returns a copy of this LocalDate with the specified number of days subtracted.
This method subtracts the specified amount from the days field decrementing the month and year fields as necessary to ensure the result remains valid. The result is only invalid if the maximum/minimum year is exceeded.

For example, 2009-01-01 minus one day would result in 2008-12-31.

This instance is immutable and unaffected by this method call.

Parameters:

daysToSubtract – the days to subtract, may be negative

Returns:

a LocalDate based on this date with the days subtracted, not null