JDK8之Instant、LocalDateTime、DateTimeFormatter

最近参与了公司新开的项目,项目中定义了时间相关,最好用LocalDateTime替换Date。去年也在公众号上有见过,但是没有深入学习,今年正好碰到,所以决定学习JDK8 的时间相关知识的同时也回顾一下Date、Calendar以及SimpleDateFormat的用法,方便进行比较。

首先Instant、LocalDateTime、DateTimeFormatter都是JDK8新增的java.time包下面的

话不多说,先把常用的时间相关的方法进行对比

1、 Instant和Date对比(主讲Instant)

// 当前时间

	Date date = new Date();
	// 当前时间为:Thu Jun 04 10:58:13 CST 2020
	System.out.println("当前时间为:" + date);
	
	Instant now = Instant.now();
	// 当前时间Instant为:2020-06-04T02:59:27.931Z
	System.out.println("当前时间Instant为:" + now);

// 返回自从GMT 1970-01-01 00:00:00到此date对象上时间的毫秒数。

	long dateTime = date.getTime();
	// Date 从1970-01-01 00:00:00到此date对象上时间的毫秒数:1591239721509
	System.out.println("Date 从1970-01-01 00:00:00到此date对象上时间的毫秒数:" + dateTime);
	
	long epochMilli = now.toEpochMilli();
	//Instant 从1970-01-01 00:00:00到此date对象上时间的毫秒数:1591239828858
	System.out.println("Instant 从1970-01-01 00:00:00到此date对象上时间的毫秒数:" + epochMilli);
	
	long epochSecond = now.getEpochSecond();
	// Instant 从1970-01-01 00:00:00到此date对象上时间的秒数:1591239949
	System.out.println("Instant 从1970-01-01 00:00:00到此date对象上时间的秒数:" + epochSecond);

// 给现在时间增加1000秒

	Instant plusSeconds = now.plusSeconds(1000);
	// 给现在时间增加1000秒:2020-06-04T03:28:45.493Z
	System.out.println("给现在时间增加1000秒:" + plusSeconds);

// 比较时间前后

	boolean flagInstant = now.isBefore(plusSeconds);
	// Instant现在时间和刚才时间加上一千秒比较,看是否在那个时间之前:true
	System.out.println("Instant现在时间和刚才时间加上一千秒比较,看是否在那个时间之前:" + flagInstant);
	
	Date date1 = new Date(2020 - 1900, 5 - 1, 3); // (2020年5月3日)
	boolean flagDate = date.before(date1); //date是否在date1之前
	// Date现在时间和2020年5月3日比较,看是否在那个时间之前:false
	System.out.println("Date现在时间和2020年5月3日比较,看是否在那个时间之前:" + flagDate);

LocalDateTime和Calendar对比(住讲LocalDateTime)

// 表示当前时间

	Calendar calendar = Calendar.getInstance();
	Date date = calendar.getTime();
	// Calendar表示当前时间:Thu Jun 04 11:34:50 CST 2020
	System.out.println("Calendar表示当前时间:" + date);
	
	LocalDateTime localDateTime = LocalDateTime.now();
	// LocalDateTime表示当前时间:2020-06-04T11:34:50.390
	System.out.println("LocalDateTime表示当前时间:" + localDateTime);

// 格式化时间

	String localDateTimeFormatTime = localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"));
	// LocalDateTime格式化时间:2020/06/04 11:43:13
	System.out.println("LocalDateTime格式化时间:" + localDateTimeFormatTime);
	
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
	String CalendarFormatTime = simpleDateFormat.format(calendar.getTime());
	// Calendar格式化时间:2020年06月04日 11:48:04
	System.out.println("Calendar格式化时间:" + CalendarFormatTime);

// 当前时间增加20分钟

	LocalDateTime localDateTimePlusTime = localDateTime.plus(20, ChronoUnit.MINUTES);
	// localDateTime当前时间增加20分钟:2020-06-04T12:14:32.745
	System.out.println("localDateTime当前时间增加20分钟:" + localDateTimePlusTime);
	
	Calendar calendar1 = Calendar.getInstance();
	calendar1.add(Calendar.MINUTE, 20);
	Date calendarPlusTime = calendar1.getTime();
	// Calendar当前时间增加20分钟:Thu Jun 04 12:14:32 CST 2020
	System.out.println("Calendar当前时间增加20分钟:" + calendarPlusTime);

// 计算两个时间的时间差

	Date dateStart = new Date(2020 - 1900, 4 - 1, 15); // 2020年4月15日
	Date dateEnd = new Date(); // 现在
	// Date时间差:50
	System.out.println("Date时间差:" + (dateEnd.getTime() - dateStart.getTime()) / 1000 / 60 / 60 / 24);
	
	LocalDateTime localDateTimeStart = LocalDateTime.of(2020, 4, 15, 15, 22);
	LocalDateTime localDateTimeEnd = LocalDateTime.of(2020, 6, 5, 13, 43);
	Duration localDateTimeDiff = Duration.between(localDateTimeEnd, localDateTimeStart);
	// LocalDateTime时间差:-50
	System.out.println("LocalDateTime时间差:" + localDateTimeDiff.toDays());

//使用LocalDateTime计算两个时间的差

        LocalDateTime now = LocalDateTime.now();
        System.out.println("计算两个时间的差:");
        LocalDateTime end = LocalDateTime.now();
        Duration duration = Duration.between(now,end);
        long days = duration.toDays(); //相差的天数
        long hours = duration.toHours();//相差的小时数
        long minutes = duration.toMinutes();//相差的分钟数
        long millis = duration.toMillis();//相差毫秒数
        long nanos = duration.toNanos();//相差的纳秒数
        System.out.println(now);
        System.out.println(end);

// 比较时间先后(LocalDateTime也可以比较时间先后)

	boolean localDateTimeCompare = localDateTimeStart.isBefore(localDateTimeEnd);
	// LocalDateTime比较时间先后:true
	System.out.println("LocalDateTime比较时间先后:" + localDateTimeCompare);
	
	Calendar c1 = Calendar.getInstance();
	Calendar c2 = Calendar.getInstance();
	c1.clear();
	c2.clear();
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	c1.setTime(sdf.parse("2020-04-15"));
	c2.setTime(sdf.parse("2020-06-05"));
	int calendarCompare = c1.compareTo(c2);
	// Calendar比较时间先后:-1(-1代表在这个时间之前,0代表相等,1代表在这个时间之后)
	System.out.println("Calendar比较时间先后:" + calendarCompare);

//获取秒数 (东8区,也就是北京时间)

	Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
	// LocalDateTime获取秒数和日常方法对比:true
	System.out.println("LocalDateTime获取秒数和日常方法对比:"+second.equals((System.currentTimeMillis())/1000));

//获取毫秒数(东8区,也就是北京时间)

	Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
	// LocalDateTime获取毫秒数和日常方法对比:true
	System.out.println("LocalDateTime获取毫秒数和日常方法对比:"+milliSecond.equals(System.currentTimeMillis()));
	Calendar c3 = Calendar.getInstance();
	Long calendarMilliSecond = c3.getTimeInMillis();
	// Calendar获取毫秒数和日常方法对比:true
	System.out.println("Calendar获取毫秒数和日常方法对比:"+calendarMilliSecond.equals(System.currentTimeMillis()));

DateTimeFormatter 和 SimpleDateFormat对比

	LocalDateTime now = LocalDateTime.now();
	// 声明日期格式
	DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
	String dateTimeFormatterStr = dateTimeFormatter.format(now);
	// DateTimeFormatter格式化时间:2020/06/04 15:36:08
	System.out.println("DateTimeFormatter格式化时间:"+dateTimeFormatterStr);
	

	Date date = new Date();
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	String simpleDateFormatStr = simpleDateFormat.format(date);
	// SimpleDateFormat格式化时间:2020/06/04 15:36:08
	System.out.println("SimpleDateFormat格式化时间:"+simpleDateFormatStr);
	
	// DateTimeFormatter已经封装好的一些格式
	LocalDateTime localDateTime = LocalDateTime.now();
	String dateTimeFormatterStr1 = localDateTime.format(DateTimeFormatter.BASIC_ISO_DATE);
	// DateTimeFormatter.BASIC_ISO_DATE格式:20200604
	System.out.println("DateTimeFormatter.BASIC_ISO_DATE格式:"+dateTimeFormatterStr1);
	/*
        ISO_DATE            --> 2019-04-24
        ISO_LOCAL_DATE      --> 2019-04-24
        ISO_LOCAL_TIME      --> 20:59:48.42
        ISO_TIME            --> 21:00:38.256
        ISO_LOCAL_DATE_TIME --> 2019-04-24T21:01:11.083*/

LocalDateTime、Instant与Date的转换

Instant和Date的相互转换

	/*
	* Instant和Date的相互转换
	* */
	Instant now = Instant.now();
	Date date = Date.from(now); // Instant转换成Date
	
	Date date1 = new Date();
	Instant instant = date1.toInstant();// Date转换成Instant

LocalDateTime 和 Date 之间的转换(Date 与 LocalDateTime 的转换是通过 Instant 中间的转换来进行的)

	/*
	* LocalDateTime 和 Date 之间的转换
	* Date 与 LocalDateTime 的转换是通过 Instant 中间的转换来进行的
	* */
	
	Date date3 = new Date();
	// Date转换成LocalDateTime
	LocalDateTime localDateTime1 = LocalDateTime.ofInstant(date3.toInstant(),ZoneId.systemDefault());
	
	LocalDateTime localDateTime = LocalDateTime.now();
	Instant instant1 = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
	Date date2 = Date.from(instant); // LocalDateTime转换为Date

总结

// 表示当前时间

	// 表示当前时间
	Date date = new Date();
	System.out.println("Date表示当前时间:" + date);
	Instant instant = Instant.now();
	System.out.println("Instant表示当前时间:" + instant);
	LocalDateTime localDateTime = LocalDateTime.now();
	System.out.println("LocalDateTime表示当前时间:" + localDateTime);
	
	
	/*
	* Date表示当前时间:Thu Jun 04 16:25:10 CST 2020
	Instant表示当前时间:2020-06-04T08:25:10.733Z
	LocalDateTime表示当前时间:2020-06-04T16:25:10.797
	* */

// 获得1970-01-01 00:00:00 到当前时间的毫秒数

	// 获得1970-01-01 00:00:00 到当前时间的毫秒数
	long currentTimeMillis = System.currentTimeMillis();
	System.out.println("System表示到当前时间的毫秒数" + currentTimeMillis);
	Date date1 = new Date();
	long date1Time = date1.getTime();
	System.out.println("Date表示到当前时间的毫秒数" + date1Time);
	Calendar calendar = Calendar.getInstance();
	long calendarTimeInMillis = calendar.getTimeInMillis();
	System.out.println("Calendar表示到当前时间的毫秒数" + calendarTimeInMillis);
	LocalDateTime localDateTime1 = LocalDateTime.now();
	long toEpochMilli = localDateTime1.toInstant(ZoneOffset.of("+8")).toEpochMilli();
	System.out.println("LocalDateTime表示到当前时间的毫秒数" + toEpochMilli);
	Instant instant1 = Instant.now();
	long epochMilli = instant1.toEpochMilli();
	System.out.println("Instant表示到当前时间的毫秒数" + epochMilli);
	
	/*
	* 
	System表示到当前时间的毫秒数1591262531070
	Date表示到当前时间的毫秒数1591262531070
	Calendar表示到当前时间的毫秒数1591262531071
	LocalDateTime表示到当前时间的毫秒数1591262531073
	Instant表示到当前时间的毫秒数1591262531073
	* */

// 判断两个时间的先后

	Date dateStart = new Date();
	Date dateEnd = new Date(2019 - 1900, 10 - 1, 5);
	boolean dateFlag = dateStart.before(dateEnd);
	System.out.println("Date比较两个时间的先后:" + dateFlag);
	int dateCompate = dateStart.compareTo(dateEnd);
	System.out.println("Date-compareTo比较两个时间的先后:" + dateCompate);
	
	LocalDateTime localDateTimeStart = LocalDateTime.now();
	LocalDateTime localDateTimeEnd = LocalDateTime.of(2019, 10, 5, 11, 00);
	boolean localDateTimeFlag = localDateTimeStart.isBefore(localDateTimeEnd);
	System.out.println("LocalDateTime比较两个时间的先后:" + localDateTimeFlag);
	
	Instant instantStart = Instant.now();
	Instant instantEnd = instantStart.plusSeconds(1000);
	boolean instantFlag = instantStart.isBefore(instantEnd);
	System.out.println("Instant比较两个时间的先后:" + instantFlag);
	
	/*
	* Date比较两个时间的先后:false
	Date-compareTo比较两个时间的先后:1
	LocalDateTime比较两个时间的先后:false
	Instant比较两个时间的先后:true
	* */

// 日期格式化

// Date和String之间的转换 - SimpleDateFormat

	// Date和String之间的转换 - SimpleDateFormat
	// Date----->String
	Date date2 = new Date();
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	String dateStr = simpleDateFormat.format(date2);
	System.out.println("Date----->String结果:" + dateStr);
	// String----->Date
	String string = "2020-06-04 17:47:00";
	Date date3 = null;
	try {
	date3 = simpleDateFormat.parse(string);
	} catch (ParseException e) {
	e.printStackTrace();
	System.out.println("String----->Date失败");
	}
	System.out.println("String----->Date结果:" + date3);
	/*
	* Date----->String结果:2020-06-04 17:49:10
	String----->Date结果:Thu Jun 04 17:47:00 CST 2020
	* */

LocalDateTime和String之间的转换 - DateTimeFormatter

	//  LocalDateTime和String之间的转换 - DateTimeFormatter
	// LocalDateTime------>String
	DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
	LocalDateTime localDateTime2 = LocalDateTime.now();
	String localDateTimeStr = localDateTime2.format(dateTimeFormatter);
	System.out.println("LocalDateTime------>String结果:" + localDateTimeStr);
	
	
	// String----->LocalDateTime
	String string1 = "2020年06月04日 17:47:00";
	LocalDateTime localDateTime3 = null;
	try {
	localDateTime3 = LocalDateTime.parse(string1, dateTimeFormatter);
	} catch (Exception e) {
	System.out.println("String----->LocalDateTime失败");
	}
	System.out.println("String----->LocalDateTime结果:" + localDateTime3);
	
	/*
	* LocalDateTime------>String结果:2020年06月04日 18:07:41
	String----->LocalDateTime结果:2020-06-04T17:47
* */

// 给当前时间+某一时间

	Instant plusSeconds = Instant.now().plusSeconds(1000);
	// 给现在时间增加1000秒:2020-06-04T03:28:45.493Z
	System.out.println("给现在时间增加1000秒:" + plusSeconds);
	// 当前时间增加20分钟
	LocalDateTime localDateTimePlusTime = LocalDateTime.now().plus(20, ChronoUnit.SECONDS);
	// localDateTime当前时间增加20分钟:2020-06-04T12:14:32.745
	System.out.println("localDateTime当前时间增加20秒:" + localDateTimePlusTime);

就Instant、LocalDateTime、DateTimeFormatter来说,LocalDateTime基本都能实现Instant,拓展也更多,所以项目中可以尽可能使用LocalDateTime,关于为什么少使用SimpleDateFormat而用LocalDateTime(线程安全问题?我不太懂这),欢迎大家评论科普

参考文章:https://www.jianshu.com/p/9828d79a2528

下篇文章讲:
时间相关的两个算法题:1、计算两个时间相差多少(getTime)2、黑色星期五
(用LocalDateTime和Date对比讲)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值