2021-11-11 Java8新特性——新一套日期时间API

Java8新特性——新一套日期时间API

JavaSE核心内容 专栏收录该内容
63 篇文章 31 订阅

文章目录:

1.新旧对比(线程安全问题)

2.LocalDate

3.LocalTime

4.LocalDateTime

5.Instant

6.Duration、Period

7.TestTemporalAdjuster、TestTemporalAdjusters

8.DateTimeFormatter


1.新旧对比(线程安全问题)

我们先来看下面的代码:👇👇👇 (关于代码中某些类中的某些方法,我在这里就不说了,大家可以去查找api文档)


     
     
  1. package com.szh.java8.datetime;
  2. import java.text.SimpleDateFormat;
  3. import java.time.LocalDate;
  4. import java.time.format.DateTimeFormatter;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.List;
  8. import java.util.concurrent.*;
  9. /**
  10. *
  11. */
  12. public class TestSimpleDateFormat {
  13. public static void main (String[] args) throws ExecutionException, InterruptedException {
  14. SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMMdd");
  15. Callable<Date> task1 = new Callable<Date>() {
  16. @Override
  17. public Date call () throws Exception {
  18. return sdf.parse( "20211109");
  19. }
  20. };
  21. ExecutorService pool1 = Executors.newFixedThreadPool( 10);
  22. List<Future<Date>> futureList1 = new ArrayList<>();
  23. for ( int i = 0; i < 10; i++) {
  24. futureList1.add(pool1.submit(task1));
  25. }
  26. for (Future<Date> future : futureList1) {
  27. System.out.println(future.get());
  28. }
  29. pool1.shutdown();
  30. //=================================================================
  31. // DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
  32. //
  33. // Callable<LocalDate> task2 = new Callable<LocalDate>() {
  34. // @Override
  35. // public LocalDate call() throws Exception {
  36. // return LocalDate.parse("20211109",dtf);
  37. // }
  38. // };
  39. //
  40. // ExecutorService pool2 = Executors.newFixedThreadPool(10);
  41. // List<Future<LocalDate>> futureList2 = new ArrayList<>();
  42. // for (int i = 0; i < 10; i++) {
  43. // futureList2.add(pool2.submit(task2));
  44. // }
  45. //
  46. // for (Future<LocalDate> future : futureList2) {
  47. // System.out.println(future.get());
  48. // }
  49. //
  50. // pool2.shutdown();
  51. }
  52. }

运行之后,就出现了线程安全问题。

将代码中的上半部分注释掉,然后打开下半部分的代码,再次运行,线程安全问题就不存在了。

也就是Java8中提供了新一套日期时间API已经解决了线程安全问题。


2.LocalDate


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.LocalDate;
  3. /**
  4. *
  5. */
  6. public class TestLocalDate {
  7. public static void main (String[] args) {
  8. LocalDate ld1 = LocalDate.now();
  9. System.out.println(ld1);
  10. LocalDate ld2 = LocalDate.of( 2021, 5, 1);
  11. System.out.println(ld2);
  12. LocalDate ld3 = ld1.plusYears( 20);
  13. System.out.println(ld3);
  14. LocalDate ld4 = ld1.minusMonths( 3);
  15. System.out.println(ld4);
  16. System.out.println(ld1.isBefore(ld2));
  17. System.out.println(ld2.isAfter(ld1));
  18. System.out.println(ld1.isLeapYear());
  19. System.out.println( "年:" + ld1.getYear() + ", 月:" + ld1.getMonth() + ", 日:" + ld1.getDayOfMonth());
  20. System.out.println( "年:" + ld1.getYear() + ", 月:" + ld1.getMonthValue() + ", 日:" + ld1.getDayOfMonth());
  21. }
  22. }

3.LocalTime


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.LocalTime;
  3. /**
  4. *
  5. */
  6. public class TestLocalTime {
  7. public static void main (String[] args) {
  8. LocalTime lt1 = LocalTime.now();
  9. System.out.println(lt1);
  10. LocalTime lt2 = LocalTime.of( 13, 14, 15);
  11. System.out.println(lt2);
  12. LocalTime lt3 = lt2.plusHours( 3);
  13. System.out.println(lt3);
  14. LocalTime lt4 = lt2.minusMinutes( 14);
  15. System.out.println(lt4);
  16. System.out.println(lt1.isBefore(lt2));
  17. System.out.println(lt2.isAfter(lt1));
  18. System.out.println( "小时:" + lt1.getHour() + ", 分钟:" + lt1.getMinute() + ", 秒:" + lt1.getSecond());
  19. }
  20. }

4.LocalDateTime


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.LocalDateTime;
  3. /**
  4. *
  5. */
  6. public class TestLocalDateTime {
  7. public static void main (String[] args) {
  8. LocalDateTime ldt1 = LocalDateTime.now();
  9. System.out.println(ldt1);
  10. LocalDateTime ldt2 = LocalDateTime.of( 2020, 5, 1, 13, 14, 15);
  11. System.out.println(ldt2);
  12. LocalDateTime ldt3 = ldt1.plusYears( 15);
  13. System.out.println(ldt3);
  14. LocalDateTime ldt4 = ldt1.minusDays( 20);
  15. System.out.println(ldt4);
  16. System.out.println(ldt1.isBefore(ldt2));
  17. System.out.println(ldt2.isAfter(ldt1));
  18. System.out.println( "年:" + ldt2.getYear() + ", 月:" + ldt2.getMonthValue() + ", 日:" + ldt2.getDayOfMonth()
  19. + ", 小时:" + ldt2.getHour() + ", 分钟:" + ldt2.getMinute() + ", 秒:" + ldt2.getSecond());
  20. }
  21. }

5.Instant


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.Instant;
  3. import java.time.OffsetDateTime;
  4. import java.time.ZoneOffset;
  5. /**
  6. * Instant : 时间戳(使用 Unix 元年 1970年1月1日 00:00:00 所经历的毫秒值)
  7. * 默认使用 UTC 时区
  8. */
  9. public class TestInstant {
  10. public static void main (String[] args) {
  11. Instant instant1 = Instant.now();
  12. System.out.println(instant1);
  13. OffsetDateTime odt = instant1.atOffset(ZoneOffset.ofHoursMinutesSeconds( 8, 16, 32));
  14. System.out.println(odt);
  15. System.out.println(instant1.getEpochSecond());
  16. System.out.println(instant1.toEpochMilli());
  17. Instant instant2 = Instant.ofEpochSecond( 1000);
  18. System.out.println(instant2);
  19. Instant instant3 = instant1.plusSeconds( 30);
  20. System.out.println(instant3);
  21. Instant instant4 = instant1.minusSeconds( 50);
  22. System.out.println(instant4);
  23. }
  24. }

6.Duration、Period


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.Duration;
  3. import java.time.LocalDate;
  4. import java.time.LocalTime;
  5. import java.time.Period;
  6. /**
  7. * Period : 用于计算两个“日期”间隔
  8. * Duration : 用于计算两个“时间”间隔
  9. */
  10. public class TestPeriodDuration {
  11. public static void main (String[] args) {
  12. LocalDate ld1 = LocalDate.now();
  13. LocalDate ld2 = LocalDate.of( 2020, 5, 1);
  14. Period period = Period.between(ld2,ld1);
  15. System.out.println( "两个日期相差:" + period.getYears() + "年," + period.getMonths() + "个月,"
  16. + period.getDays() + "天....");
  17. System.out.println(period.isNegative()); //检查此期间的三个单位是否为负
  18. System.out.println(period.isZero()); //检查此期间的所有三个单位是否为零
  19. System.out.println( "--------------------------------------------");
  20. LocalTime lt1 = LocalTime.now();
  21. try {
  22. Thread.sleep( 2000);
  23. } catch (InterruptedException e) {
  24. e.printStackTrace();
  25. }
  26. LocalTime lt2 = LocalTime.now();
  27. Duration duration = Duration.between(lt1,lt2);
  28. System.out.println( "两个时间相差:" + duration.toHours() + "个小时," + duration.toMinutes() + "分钟,"
  29. + duration.getSeconds() + "秒....");
  30. System.out.println(duration.isNegative()); //检查此期间的三个单位是否为负
  31. System.out.println(duration.isZero()); //检查此期间的所有三个单位是否为零
  32. }
  33. }

7.TestTemporalAdjuster、TestTemporalAdjusters


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.DayOfWeek;
  3. import java.time.LocalDateTime;
  4. import java.time.temporal.TemporalAdjusters;
  5. /**
  6. * TemporalAdjuster : 时间校正器。有时我们可能需要获取例如:将日期调整到“下个周日”等操作。
  7. * TemporalAdjusters : 该类通过静态方法提供了大量的常用 TemporalAdjuster 的实现。
  8. */
  9. public class TestTemporalAdjuster {
  10. public static void main (String[] args) {
  11. LocalDateTime ldt1 = LocalDateTime.now();
  12. System.out.println(ldt1);
  13. LocalDateTime ldt2 = ldt1.withMonth( 5);
  14. System.out.println(ldt2);
  15. LocalDateTime ldt3 = ldt1.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
  16. System.out.println(ldt3);
  17. //自定义:下一个工作日
  18. LocalDateTime ldt4 = ldt1.with((l) -> {
  19. LocalDateTime ldt5 = (LocalDateTime) l;
  20. DayOfWeek dow = ldt5.getDayOfWeek();
  21. if (dow.equals(DayOfWeek.FRIDAY)) {
  22. return ldt5.plusDays( 3);
  23. } else if (dow.equals(DayOfWeek.SATURDAY)) {
  24. return ldt5.plusDays( 2);
  25. } else {
  26. return ldt5.plusDays( 1);
  27. }
  28. });
  29. System.out.println(ldt4);
  30. }
  31. }

8.DateTimeFormatter


     
     
  1. package com.szh.java8.datetime;
  2. import java.time.LocalDateTime;
  3. import java.time.format.DateTimeFormatter;
  4. /**
  5. * 解析与格式化
  6. */
  7. public class TestDateTimeFormatter {
  8. public static void main (String[] args) {
  9. DateTimeFormatter dtf1 = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
  10. LocalDateTime ldt1 = LocalDateTime.now();
  11. String strDate1 = ldt1.format(dtf1);
  12. System.out.println(strDate1);
  13. System.out.println( "-----------------------------------");
  14. DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern( "yyyy年MM月dd日 HH:mm:ss");
  15. String strDate2 = ldt1.format(dtf2);
  16. System.out.println(strDate2);
  17. System.out.println( "-----------------------------------");
  18. LocalDateTime newDate = ldt1.parse(strDate2, dtf2);
  19. System.out.println(newDate);
  20. }
  21. }

</article>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值