好吧,Java8已经出来这么久了但是在处理日期时间上还是主要使用3个类,Date
、SimpleDateFormat
和Calendar
。
但是SimpleDateFormat
不是线程安全的,Date
和Calendar
获取到的月份是0到11,而不是现实生活中的1到12,很容易犯错。所以篇讲解下JDK8推出的日期时间类。
Instant
获取当前时间
Instant instant = Instant.now();
System.out.println(instant);如果要输出北京时间则需要加上默认事件
System.out.println(instant.atZone(ZoneId.systemDefault()));
将String转换为Instant
String text = "2018-06-10T08:46:55.967Z"; Instant parseInstant = Instant.parse(text); System.out.println("秒时间戳:" + parseInstant.getEpochSecond()); System.out.println("豪秒时间戳:" + parseInstant.toEpochMilli()); System.out.println("纳秒:" + parseInstant.getNano());
LocalDate
获取当前日期
LocalDate today = LocalDate.now(); System.out.println("today: " + today);
输出结果
today: 2019-03-15获取年月日
LocalDate today = LocalDate.now();
int year = today.getYear();
int month = today.getMonthValue();
int day = today.getDayOfMonth();
LocalDateTime
获取当前时间、年月时分秒
LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("localDateTime:" + localDateTime);
System.out.println("year: " + localDateTime.getYear());
System.out.println("month: " + localDateTime.getMonthValue());
System.out.println("day: " + localDateTime.getDayOfMonth());
System.out.println("hour: " + localDateTime.getHour());
System.out.println("minute: " + localDateTime.getMinute());
System.out.println("second: " + localDateTime.getSecond());增加/减少天数/小时
LocalDateTime localDateTime = LocalDateTime.now(); System.out.println("localDateTime: " + localDateTime); LocalDateTime tomorrow = localDateTime.plusDays(1); System.out.println("tomorrow: " + tomorrow); LocalDateTime nextHour = localDateTime.plusHours(1); System.out.println("nextHour: " + nextHour);
LocalDateTime yesterday = localDateTime.minusDays(1);
System.out.println("yesterday: " + yesterday);
LocalDateTime lastHour = localDateTime.minusHours(1);
System.out.println("lastHour: " + lastHour);
DateTimeFormatter
格式化日期
LocalDate localDate = LocalDate.now(); System.out.println("yyyy/MM/dd: " + localDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
输出结果:yyyy/MM/dd: 2020/06/11
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime);
System.out.println("ISO_DATE_TIME: " + localDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
System.out.println("ISO_DATE: " + localDateTime.format(DateTimeFormatter.ISO_DATE));类型相互转换
Instant转Date
Date转Instant
Date转LocalDateTime
推荐使用Instant
代替Date
,LocalDateTime
代替 Calendar
,DateTimeFormatter
代替 SimpleDateFormat
- 本文标题: Java8日期使用
- 文章作者: sherryriver(木木三可)
- 发布时间: 2019.03.15
- 本文链接: https://sherryriver.github.io/2019/03/15/java8日期使用/
- 许可协议: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。