一,Java8之后,对于日期有哪些优化?
在Java8之前,日期时间API一直被开发者诟病,包括:java.util.Date是可变类型,Calendar类也有很多设计的问题和缺陷,使用不方便SimpleDateFormat非线程安全等问题。故此,Java8引入了一套全新的日期时间处理API,新的API基于ISO标准日历系统。
二,常用日期操作
1.获取时间日期格式
Instant:时间戳
Duration:持续时间,时间差
LocalDate:只包含日期,比如2018-12-02
LocalTime:只包含时间,比如10:25:56
LocalDateTime:包含日期和时间,比如2018-12-02 10:26:37
Period:时间段
ZoneOffset:时区偏移量,比如+8:00
ZonedDateTime:带时区的时间,比如2018-12-02T10:29:49.465+08:00[Asia/Shanghai]
Clock:时钟,比如获取美国纽约的时间
LocalDate date = LocalDate.now();
logger.info("当前日期是:{}", date);
LocalDateTime nowTime = LocalDateTime.now();
String newDateTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//月份是:SEPTEMBER,月份的几天:11
logger.info("当前时间是:{}", newDateTime);
LocalTime localTime = LocalTime.now();
logger.info("当前时间是:{}", localTime);
结果:
当前日期是:2019-09-12
当前时间是:2019-09-12 11:18:51
月份是:SEPTEMBER,月份的几天:12
构造日期是:2019-04-06 12:04:00
2.格式化日期
LocalDateTime nowTime = LocalDateTime.now();
String newDateTime = nowTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//月份是:SEPTEMBER,月份的几天:11
logger.info("当前时间是:{}", newDateTime);
//字符串转化为日期
String wantDate = "2019-09-11 11:11:11";
LocalDateTime parse = LocalDateTime.parse(wantDate, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
logger.info("字符串转化为日期为:{}", parse);
3.日期增加减少
//日期计,增加几天(小时等)
LocalTime computeTime1 = LocalTime.now().plusHours(-2);
//plusHours增加日期量 09:00:07.499
logger.info("时间计算一:{}", computeTime1);
//不同的计量单位
LocalDate computeDate = LocalDate.now().plus(10, ChronoUnit.DAYS);
//重要的类 ChronoUnit (纳秒,微妙,毫秒,秒,分钟,小时,天,周,月,年)
//日期计算一: 2019-09-21
logger.info("日期计算一:{}", computeDate);
4.日期比较(日期前后,是否相等)
//日期比较
LocalDate dateTest = LocalDate.now();
logger.info("结果是:{}", dateTest);
boolean before = dateTest.isBefore(LocalDate.of(2019, 12, 1));
boolean after = dateTest.isAfter(LocalDate.of(2010, 12, 12));
logger.info("是否在前面:{},after测试:{}", before, after);
boolean equalResult = startDateTime.equals(endDateTime);
logger.info("日期是否相等:{}", equalResult);
5. 求两个日期的时间段
//日期格式差值
String pattern = "yyyy-MM-dd";
LocalDate startDate = LocalDate.parse("2019-09-12", DateTimeFormatter.ofPattern(pattern));
LocalDate endDate = LocalDate.parse("2019-09-13", DateTimeFormatter.ofPattern(pattern));
Period between = Period.between(startDate, endDate);
logger.info("相差天数是:{}", between.getDays());
//求两个时间的差值
String dateTimePattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime startDateTime = LocalDateTime.parse("2019-09-12 11:11:11", DateTimeFormatter.ofPattern(dateTimePattern));
LocalDateTime endDateTime = LocalDateTime.parse("2019-09-11 11:11:11", DateTimeFormatter.ofPattern(dateTimePattern));
Long days = Duration.between(startDateTime, endDateTime).toDays();
logger.info("相差几天:{}", Math.abs(days));
这段时间有个需求,就是需要求日期之前的间隔;
现在需要搞一个活动,活动开始前, 第一天赠送1金币ÿ