Learn how to find start and end date 30 days Ago in Java 8 from the current date using LocalDate and DateTimeFormatter. A LocalDate provides methods for date manipulation such as adding or subtracting days, months, and years.
Code Explanation (Step-by-Step)
- Creates a LocalDate object representing the current date using LocalDate.now() .
- Uses minusDays(30) to calculate the date that is 30 days before the current date.
- Creates a formatter using DateTimeFormatter.ISO_DATE to format dates in yyyy-MM-dd format.
- Formats both dates into String values using the format() method.
- Stores the start date and end date in a HashMap as key-value pairs.
- Prints the start date and end date from the dateParams map.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
public class MinusDaysProgram {
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate startDate = currentDate.minusDays(30);
DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE;
Map dateParams = new HashMap();
String startDateString = startDate.format(formatter);
String endDateString = currentDate.format(formatter);
dateParams.put("start_date", startDateString);
dateParams.put("end_date", endDateString);
System.out.println("Find start and end date after subtracting 30 days: " + dateParams);
}
}
Output :
Find start and end date after subtracting 30 days : {end_date=2025-05-22, start_date=2025-04-22}
Java 8 Program to Get Last 30 Days Date Range
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Last30DaysRange {
public static void main(String[] args) {
LocalDate endDate = LocalDate.now();
LocalDate startDate = endDate.minusDays(30);
long daysBetween = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("Start Date : " + startDate);
System.out.println("End Date : " + endDate);
System.out.println("Total Days : " + daysBetween);
}
}
`
Here are some related Java 8 programs that will help you understand Stream API concepts better:
FAQ
How do I get the current date in Java 8?
Use LocalDate.now() to get the current system date.
How can I subtract 30 days from a date in Java?
Use the minusDays(30) method on a LocalDate object.
What is DateTimeFormatter.ISO_DATE?
It formats dates in ISO-8601 format, such as 2025-05-20.
Why use LocalDate instead of Date?
LocalDate is part of the modern Java Date-Time API and is more readable, immutable, and thread-safe.
Can I subtract months or years instead of days?
Yes, you can use minusMonths() and minusYears() methods.