JDK8中关于java.time的类的简单使用

看编码规范的时候,要求注意线程安全

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);

输出结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值