Methods for date addition and subtraction in java
In Java, the date and subtraction operation is one of the common requirements.Whether it is to deal with business logic, data analysis, or generate reports, the date is often required to perform addition and subtraction operations.Java provides a variety of methods to achieve the date and subtraction operation of the date, and introduce a new date time library after JDK 8, making the date operation more flexible and easy to use.
1. Use the Calendar class (JDK 1.1+):
The Calendar class is the date and time operation category provided by Java, which can operate and subtract the date through it.It provides the ADD method to achieve the date addition or subtraction. The first parameter represents the date field (such as the year, month, day, etc.), and the second parameter represents the value to be added and subtracted.
import java.util.Calendar;
import java.util.Date;
public class DateUtil {
public static Date addDays(Date date, int daysToAdd) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);
return calendar.getTime();
}
public static Date subtractDays(Date date, int daysToSubtract) {
return addDays(date, -daysToSubtract);
}
public static void main(String[] args) {
Date currentDate = new Date();
Date futureDate = addDays(currentDate, 5);
Date pastDate = subtractDays(currentDate, 3);
System.out.println("Future date: " + futureDate);
System.out.println("Past date: " + pastDate);
}
}
2. Use the LocalDate class of Java 8:
The Java 8 introduces a new date library, where the LocalDate class provides some convenient methods to achieve the date and subtraction operation of the date.Its PlusDays and Minusdays methods can be used to increase the number of days.
import java.time.LocalDate;
public class DateUtil {
public static LocalDate addDays(LocalDate date, int daysToAdd) {
return date.plusDays(daysToAdd);
}
public static LocalDate subtractDays(LocalDate date, int daysToSubtract) {
return date.minusDays(daysToSubtract);
}
public static void main(String[] args) {
LocalDate currentDate = LocalDate.now();
LocalDate futureDate = addDays(currentDate, 5);
LocalDate pastDate = subtractDays(currentDate, 3);
System.out.println("Future date: " + futureDate);
System.out.println("Past date: " + pastDate);
}
}
No matter which method is used, it can easily achieve the date and subtraction operation of the date.In specific business scenarios, you can choose the appropriate way according to the needs.