jdk8之前,java中做时间处理时一般会采用java.util.Date,大多吐槽Date的是其对于月份的处理是从0开始的,取得正确月份还得往后偏移一位。Date内容很丰富,不但包含年月日,还包含时间。jdk8之后,我们有更好的选择 – java.time.LocalDate。
这是jdk8中新增的日期处理类,同时新增的还有java.time.LocalTime、java.time.LocalDateTime等。
相比Date来说,LoalDate更安全、更精确也更明确。LocalDate不包含时间,只是单纯的年月日,要精确到时分秒甚至毫秒的就需要用java.time.LocalDateTime了。
一些常用的方法:
//获取点当前时间对象
LocalDate now = LocalDate.now();//输出 : 2018-09-08
//今年是哪一年
int dayofYear = now.getDayOfYear();
//今天是哪一月
int month = now.getMonth().getValue();
// 今天是几号
int dayofMonth = now.getDayOfMonth();
// 今天是周几
int dayofWeek = now.getDayOfWeek().getValue();
//设置指定日期的时间对象:
LocalDate appoint = LocalDate.parse("2018-12-07");
//计算两个日期相差多少天:
long differ = appoint.toEpochDay()-now.toEpochDay() // differ : 90
//指定天数的加减
LocalDate minus = now.minusDays(10);
System.out.println(minus); //minus : 2018-08-29
LocalDate plus =