看编码规范的时候,要求注意线程安全
SimpleDateFormat 是线程不安全的类,一般不要定义为 static 变量,如果定义为
static,必须加锁,或者使用 DateUtils 工具类。
如果是 JDK8 的应用,可以使用 Instant 代替 Date, LocalDateTime 代替 Calendar,
DateTimeFormatter 代替 SimpleDateFormat,官方给出的解释: simple beautiful strong immutable
thread-safe
所以来学习一下JDK8的这几个关于时间使用的类的用法
Instant
Instant
是一个代替java.util.Date
的类,用来表示当前时间
//获取当前时间
Instant instant = Instant.now();
Instant
有两个属性,一个是秒数epochSecond
,一个是纳秒数nano
,
运行如下代码可以看出区别.
Instant instant = Instant.now();
Date date = new Date();
System.out.println("Instant:" + instant);
System.out.println("Date:" + date);
System.out.println("Instant.epochSecond:" + instant.getEpochSecond());
System.out.println("Instant.Nano" + instant.getNano());
System.out.println("Date.time:" + date.getTime());
运行结果
LocalDateTime
LocalDateTime
是一个替代Calendar
类的类,可以指定日期获取时间或获取日期的时分秒年月日等属性并进行修改等操作
// 获取当前时间
LocalDateTime localDateTime = LocalDateTime.now();
//指定年月日时分秒获取特定时间
LocalDateTime specificTime = LocalDateTime.of(2019,8,25,14,13,9).format(dateTimeFormatter);
// 获取时间的年月日时分秒
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
System.out.println(year + "年" + month.getValue() + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒");
DateTimeFormatter
替代SimpleDateFormat
的格式化日期时间的类
用法:
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//时间转字符串
String timeToString = LocalDateTime.of(2019,8,25,14,13,9).format(dateTimeFormatter);
//字符串转时间
LocalDateTime stringToTime = LocalDateTime.parse("2020-01-02 13:14:09", dateTimeFormatter);
System.out.println("时间转字符串:" + timeToString);
System.out.println("字符串转时间:" + stringToTime);
输出结果: