基于jdk8的日期时间计算工具类
时间: 2023-10-18 15:03:36 浏览: 98
日期时间处理工具类
以下是一个基于jdk8的日期时间计算工具类的示例代码:
```
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
public class DateUtil {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm:ss");
private static final DateTimeFormatter DATE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
public static String formatDate(LocalDate date) {
return DATE_FORMAT.format(date);
}
public static String formatTime(LocalTime time) {
return TIME_FORMAT.format(time);
}
public static String formatDateTime(LocalDateTime dateTime) {
return DATE_TIME_FORMAT.format(dateTime);
}
public static LocalDate parseDate(String dateStr) {
return LocalDate.parse(dateStr, DATE_FORMAT);
}
public static LocalTime parseTime(String timeStr) {
return LocalTime.parse(timeStr, TIME_FORMAT);
}
public static LocalDateTime parseDateTime(String dateTimeStr) {
return LocalDateTime.parse(dateTimeStr, DATE_TIME_FORMAT);
}
public static LocalDate addDays(LocalDate date, int days) {
return date.plusDays(days);
}
public static LocalDateTime addHours(LocalDateTime dateTime, int hours) {
return dateTime.plusHours(hours);
}
public static LocalDateTime addMinutes(LocalDateTime dateTime, int minutes) {
return dateTime.plusMinutes(minutes);
}
public static LocalDateTime addSeconds(LocalDateTime dateTime, int seconds) {
return dateTime.plusSeconds(seconds);
}
public static Period getPeriod(LocalDate startDate, LocalDate endDate) {
return Period.between(startDate, endDate);
}
public static long getSeconds(LocalDateTime startDateTime, LocalDateTime endDateTime) {
return startDateTime.until(endDateTime, java.time.temporal.ChronoUnit.SECONDS);
}
public static long getMinutes(LocalDateTime startDateTime, LocalDateTime endDateTime) {
return startDateTime.until(endDateTime, java.time.temporal.ChronoUnit.MINUTES);
}
public static long getHours(LocalDateTime startDateTime, LocalDateTime endDateTime) {
return startDateTime.until(endDateTime, java.time.temporal.ChronoUnit.HOURS);
}
public static long getDays(LocalDate startDate, LocalDate endDate) {
return startDate.until(endDate, java.time.temporal.ChronoUnit.DAYS);
}
}
```
这个工具类包含了日期时间格式化、解析、加减、差值计算等常用操作。使用该工具类可以方便地处理日期时间计算相关的业务需求。
阅读全文