java8 LocalDate 使用详解

2022-07-30,,

localdate

看看新的localdate怎么用:

// 取当前日期:

localdate today = localdate.now(); // -> 2019-03-29

// 根据年月日取日期,04月就是04:

localdate crischristmas = localdate.of(2019, 04, 22); // -> 2019-04-22

// 根据字符串取:

localdate endoffeb = localdate.parse(“2019-03-28”); // 严格按照iso yyyy-mm-dd验证,03写成3都不行,当然也有一个重载

方法允许自己定义格式

localdate.parse(“2019-02-31”); // 无效日期无法通过:datetimeparseexception: invalid date

日期转换经常遇到,比如:

// 取本月第1天:

localdate firstdayofthismonth = today.with(temporaladjusters.firstdayofmonth()); // 2019-03-01

// 取本月第2天:

localdate seconddayofthismonth = today.withdayofmonth(2); // 2019-03-02

// 取本月最后一天,再也不用计算是28,29,30还是31:

localdate lastdayofthismonth = today.with(temporaladjusters.lastdayofmonth()); // 2019-03-31

// 取下一天:

localdate firstdayofnextmonth = lastdayofthismonth.plusdays(1); // 变成了2019-04-01

// 取2019年1月第一个周一,这个计算用calendar要死掉很多脑细胞:

localdate firstmondayof2015 = localdate.parse(“2019-01-01”).with(temporaladjusters.firstinmonth(dayofweek.monday)); // 2019-01-05

localtime

localtime只包含时间,以前用java.util.date怎么才能只表示时间呢?答案是,假装忽略日期。

localtime包含毫秒:

localtime now = localtime.now(); // 11:09:09.240

你可能想清除毫秒数:

localtime now = localtime.now().withnano(0)); // 11:09:09

构造时间也很简单:

localtime zero = localtime.of(0, 0, 0); // 00:00:00

localtime mid = localtime.parse(“12:00:00”); // 12:00:00

时间也是按照iso格式识别,但可以识别以下3种格式:

12:00

12:01:02

12:01:02.345

jdbc

最新jdbc映射将把数据库的日期类型和java 8的新类型关联起来:

sql -> java

date -> localdate

time -> localtime

timestamp -> localdatetime

补充知识:java中算法排序是计算时间差值,java8中的duration类

duration与period相对应,period用于处理日期,而duration计算时间差还可以处理具体的时间,也是通过调用其静态的between方法,该方法为between(temporal startinclusive,temporal endexclusive),因此可以传入两个instant的实例(instant实现了temporal接口),并可以以毫秒(tomills)、秒(getseconds)等多种形式表示得到的时间差。

public static void main(string[] agrs) {
 
 int n = 10;
 int[] arr = sorttesthelper.generaterandomarray(n, 0, n);
 int[] arr2 = sorttesthelper.copy(arr, n);
 // int[] te=new int[]{2,6,3,1,4,7,5,8,9,10};
 system.out.println(); 
 instant start_time = instant.now();// 开始时间
 selectsort.selectsort(arr, n);
 instant end_time = instant.now();// 结束时间
 sorttesthelper.printarray(arr, n);
 system.out.println("时间差为:" + duration.between(start_time, end_time).tomillis());
 
 start_time = instant.now();// 开始时间
 insertionsort.insertionsort(arr2, n);
 end_time = instant.now();// 结束时间
 sorttesthelper.printarray(arr2, n);
 system.out.println("时间差为:" + duration.between(start_time, end_time).tomillis());
 
 }

以上这篇java8 localdate 使用详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

《java8 LocalDate 使用详解.doc》

下载本文的Word格式文档,以方便收藏与打印。