整理一下java1.8常用日期函数
- 时间戳转化,时间类型转化
//时间戳转化为日期格式 String类型接收
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String a = sf.format(new Date(Long.valueOf("1574928390000")));
System.out.println(a);
//时间戳转化为日期格式 LocalDate类型接收
LocalDate b = LocalDate.parse(DateUtil.getDateByTime(DateUtil.DATE_PATTERN_SIMPLE,
1574928390), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
System.out.println(b);
//String日期格式转化为LocalDate
LocalDate c = LocalDate.parse("2020-03-03");
//String时间转为LocalTime
String time = "09:00:00";
System.out.println(LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm:ss")));
//LocalDateTime 转LocalTime
LocalDateTime.now().toLocalTime();
//localdateTime转时间戳
LocalDateTime.now().plusDays(-7).toEpochSecond(ZoneOffset.of("+8"))
//时间戳转LocalDateTime
LocalDateTime.ofEpochSecond(listRedPacketDrawDO.getSendTime(), 0, ZoneOffset.ofHours(8)).toString()
- 获取当前时间
//时间戳,单位/s
System.out.println(Instant.now().getEpochSecond());
//时间戳 单位/ms
System.out.println(Instant.now().toEpochMilli());
//yyyy-MM-dd HH:mm:ss
System.out.println(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
- 获取当前日期
//yyyyMMdd
System.out.println(LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE));
//yyyy-MM-dd
System.out.println(LocalDate.now());
- 单独获取当前年,月,日,时间
//获取年
System.out.println(LocalDate.now().getYear());
//当前为一年中的第几天
System.out.println(LocalDate.now().getDayOfYear());
//获取月份(英文月份名)
System.out.println(LocalDate.now().getMonth());
//获取月份(数字)
System.out.println(LocalDate.now().getMonth().getValue());
//当前为一月中的第几天
System.out.println(LocalDate.now().getDayOfMonth());
//小时
System.out.println(LocalDateTime.now().getHour());
//分钟
System.out.println(LocalDateTime.now().getMinute());
//秒
System.out.println(LocalDateTime.now().getSecond());
- 获取间隔日期
//昨日日期
System.out.println(LocalDate.now().plusDays(-1));
//10天后的日期
System.out.println(LocalDate.now().plusDays(10));
//一周前
System.out.println(LocalDate.now().plusWeeks(-1));
//一个月前
System.out.println(LocalDate.now().plusMonths(-1));
//一年前
System.out.println(LocalDate.now().plusYears(-1));
- 计算两个日期之间的天数,月份,年份差
//日期差
System.out.println(Period.between(LocalDate.now().plusDays(-5), LocalDate.now()).getDays());
//月份差
System.out.println(Period.between(LocalDate.now().plusDays(-5), LocalDate.now()).getMonths());