深入理解Java8新特性之新日期时间API的应用
短信预约 -IT技能 免费直播动态提醒
1.新旧对比(线程安全问题)
我们先来看下面的代码:👇👇👇 (关于代码中某些类中的某些方法,我在这里就不说了,大家可以去查找api文档)
package com.szh.java8.datetime;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
public class TestSimpleDateFormat {
public static void main(String[] args) throws ExecutionException, InterruptedException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Callable<Date> task1 = new Callable<Date>() {
@Override
public Date call() throws Exception {
return sdf.parse("20211109");
}
};
ExecutorService pool1 = Executors.newFixedThreadPool(10);
List<Future<Date>> futureList1 = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futureList1.add(pool1.submit(task1));
}
for (Future<Date> future : futureList1) {
System.out.println(future.get());
}
pool1.shutdown();
//=================================================================
// DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
//
// Callable<LocalDate> task2 = new Callable<LocalDate>() {
// @Override
// public LocalDate call() throws Exception {
// return LocalDate.parse("20211109",dtf);
// }
// };
//
// ExecutorService pool2 = Executors.newFixedThreadPool(10);
// List<Future<LocalDate>> futureList2 = new ArrayList<>();
// for (int i = 0; i < 10; i++) {
// futureList2.add(pool2.submit(task2));
// }
//
// for (Future<LocalDate> future : futureList2) {
// System.out.println(future.get());
// }
//
// pool2.shutdown();
}
}
运行之后,就出现了线程安全问题。
将代码中的上半部分注释掉,然后打开下半部分的代码,再次运行,线程安全问题就不存在了。
也就是Java8中提供了新一套日期时间API已经解决了线程安全问题。
2.LocalDate
package com.szh.java8.datetime;
import java.time.LocalDate;
public class TestLocalDate {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.now();
System.out.println(ld1);
LocalDate ld2 = LocalDate.of(2021,5,1);
System.out.println(ld2);
LocalDate ld3 = ld1.plusYears(20);
System.out.println(ld3);
LocalDate ld4 = ld1.minusMonths(3);
System.out.println(ld4);
System.out.println(ld1.isBefore(ld2));
System.out.println(ld2.isAfter(ld1));
System.out.println(ld1.isLeapYear());
System.out.println("年:" + ld1.getYear() + ", 月:" + ld1.getMonth() + ", 日:" + ld1.getDayOfMonth());
System.out.println("年:" + ld1.getYear() + ", 月:" + ld1.getMonthValue() + ", 日:" + ld1.getDayOfMonth());
}
}
3.LocalTime
package com.szh.java8.datetime;
import java.time.LocalTime;
public class TestLocalTime {
public static void main(String[] args) {
LocalTime lt1 = LocalTime.now();
System.out.println(lt1);
LocalTime lt2 = LocalTime.of(13,14,15);
System.out.println(lt2);
LocalTime lt3 = lt2.plusHours(3);
System.out.println(lt3);
LocalTime lt4 = lt2.minusMinutes(14);
System.out.println(lt4);
System.out.println(lt1.isBefore(lt2));
System.out.println(lt2.isAfter(lt1));
System.out.println("小时:" + lt1.getHour() + ", 分钟:" + lt1.getMinute() + ", 秒:" + lt1.getSecond());
}
}
4.LocalDateTime
package com.szh.java8.datetime;
import java.time.LocalDateTime;
public class TestLocalDateTime {
public static void main(String[] args) {
LocalDateTime ldt1 = LocalDateTime.now();
System.out.println(ldt1);
LocalDateTime ldt2 = LocalDateTime.of(2020,5,1,13,14,15);
System.out.println(ldt2);
LocalDateTime ldt3 = ldt1.plusYears(15);
System.out.println(ldt3);
LocalDateTime ldt4 = ldt1.minusDays(20);
System.out.println(ldt4);
System.out.println(ldt1.isBefore(ldt2));
System.out.println(ldt2.isAfter(ldt1));
System.out.println("年:" + ldt2.getYear() + ", 月:" + ldt2.getMonthValue() + ", 日:" + ldt2.getDayOfMonth()
+ ", 小时:" + ldt2.getHour() + ", 分钟:" + ldt2.getMinute() + ", 秒:" + ldt2.getSecond());
}
}
5.Instant
package com.szh.java8.datetime;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
public class TestInstant {
public static void main(String[] args) {
Instant instant1 = Instant.now();
System.out.println(instant1);
OffsetDateTime odt = instant1.atOffset(ZoneOffset.ofHoursMinutesSeconds(8,16,32));
System.out.println(odt);
System.out.println(instant1.getEpochSecond());
System.out.println(instant1.toEpochMilli());
Instant instant2 = Instant.ofEpochSecond(1000);
System.out.println(instant2);
Instant instant3 = instant1.plusSeconds(30);
System.out.println(instant3);
Instant instant4 = instant1.minusSeconds(50);
System.out.println(instant4);
}
}
6.Duration、Period
package com.szh.java8.datetime;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
public class TestPeriodDuration {
public static void main(String[] args) {
LocalDate ld1 = LocalDate.now();
LocalDate ld2 = LocalDate.of(2020,5,1);
Period period = Period.between(ld2,ld1);
System.out.println("两个日期相差:" + period.getYears() + "年," + period.getMonths() + "个月,"
+ period.getDays() + "天....");
System.out.println(period.isNegative()); //检查此期间的三个单位是否为负
System.out.println(period.isZero()); //检查此期间的所有三个单位是否为零
System.out.println("--------------------------------------------");
LocalTime lt1 = LocalTime.now();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LocalTime lt2 = LocalTime.now();
Duration duration = Duration.between(lt1,lt2);
System.out.println("两个时间相差:" + duration.toHours() + "个小时," + duration.toMinutes() + "分钟,"
+ duration.getSeconds() + "秒....");
System.out.println(duration.isNegative()); //检查此期间的三个单位是否为负
System.out.println(duration.isZero()); //检查此期间的所有三个单位是否为零
}
}
7.TestTemporalAdjuster、TestTemporalAdjusters
package com.szh.java8.datetime;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class TestTemporalAdjuster {
public static void main(String[] args) {
LocalDateTime ldt1 = LocalDateTime.now();
System.out.println(ldt1);
LocalDateTime ldt2 = ldt1.withMonth(5);
System.out.println(ldt2);
LocalDateTime ldt3 = ldt1.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
System.out.println(ldt3);
//自定义:下一个工作日
LocalDateTime ldt4 = ldt1.with((l) -> {
LocalDateTime ldt5 = (LocalDateTime) l;
DayOfWeek dow = ldt5.getDayOfWeek();
if (dow.equals(DayOfWeek.FRIDAY)) {
return ldt5.plusDays(3);
} else if (dow.equals(DayOfWeek.SATURDAY)) {
return ldt5.plusDays(2);
} else {
return ldt5.plusDays(1);
}
});
System.out.println(ldt4);
}
}
8.DateTimeFormatter
package com.szh.java8.datetime;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class TestDateTimeFormatter {
public static void main(String[] args) {
DateTimeFormatter dtf1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
LocalDateTime ldt1 = LocalDateTime.now();
String strDate1 = ldt1.format(dtf1);
System.out.println(strDate1);
System.out.println("-----------------------------------");
DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String strDate2 = ldt1.format(dtf2);
System.out.println(strDate2);
System.out.println("-----------------------------------");
LocalDateTime newDate = ldt1.parse(strDate2, dtf2);
System.out.println(newDate);
}
}
以上就是深入理解Java8新特性之新日期时间API的应用的详细内容,更多关于Java 日期时间API的资料请关注编程网其它相关文章!
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341