1.日期时间处理类
- JDK8通过发布新的Date-Time API(JSR 310)来进一步加强对日期与时间的处理
- 新增了很多常见的API,如日期/时间的比较,加减,格式化等
- 包所在位置java.time
- 核心类
LocalDate:日期 LocalTime:时间 LocalDateTime:日期时间
- 常见API
LocalDate today = LocalDate.now(); System.out.println(today); //getYear() int 获取当前日期的年份 //getMonth() Month 获取当前日期的月份对象 //getMonthValue() int 获取当前日期是第几月 //getDayOfWeek() DayOfWeek 表示该对象表示的日期是星期几 //getDayOfMonth() int 表示该对象表示的日期是这个月第几天 //getDayOfYear() int 表示该对象表示的日期是今年第几天 //withYear(int year) LocalDate 修改当前对象的年份 //withMonth(int month) LocalDate 修改当前对象的月份 //withDayOfMonth(int dayOfMonth) LocalDate 修改当前对象在当月的日期 //plusYears(long yearsToAdd) LocalDate 当前对象增加指定的年份数 //plusMonths(long monthsToAdd) LocalDate 当前对象增加指定的月份数 //plusWeeks(long weeksToAdd) LocalDate 当前对象增加指定的周数 //plusDays(long daysToAdd) LocalDate 当前对象增加指定的天数 //minusYears(long yearsToSubtract) LocalDate 当前对象减去指定的年数 //minusMonths(long monthsToSubtract) LocalDate 当前对象减去指定的月数 //minusWeeks(long weeksToSubtract) LocalDate 当前对象减去指定的周数 //minusDays(long daysToSubtract) LocalDate 当前对象减去指定的天数 //compareTo(ChronoLocalDate other) int 比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚 //isBefore(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之前 //isAfter(ChronoLocalDate other) boolean 比较当前对象日期是否在other对象日期之后 //isEqual(ChronoLocalDate other) boolean 比较两个日期对象是否相等
2.日期时间格式化和计算时间差
- 常用的占位符
y 四位数年份 M 月 d 日 H 时(24小时制) h 时(12小时制) m 分 s 秒 S 毫秒
- JDK8之后,引入线程安全的日期时间转换类DateTimeFormatter
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class Test { public static void main(String[] args) { LocalDateTime today = LocalDateTime.now(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formatDate = dtf.format(today); System.out.println(formatDate); } }
- 计算日期时间差java.time.Duration
import java.time.Duration; import java.time.LocalDateTime; public class Test { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); LocalDateTime old = LocalDateTime.of(2020, 1, 20, 15, 58, 0); Duration duration = Duration.between(old, now); System.out.println(duration.toDays());// 相差的天数 System.out.println(duration.toHours());// 相差的小时数 System.out.println(duration.toMinutes());// 相差的分钟数 System.out.println(duration.toMillis());// 相差的毫秒数 System.out.println(duration.toNanos());// 相差的纳秒数 } }