当前位置:   article > 正文

java8新特性_18_新时期与日期API_本地时间和时间戳_18may20java

18may20java
  1. @Test
  2. public void test1(){
  3. LocalDateTime ldt = LocalDateTime.now();
  4. System.out.println(ldt);
  5. LocalDateTime ldt2 = LocalDateTime.of(2019, 9, 26, 21, 48);
  6. System.out.println(ldt2);
  7. //可以进行年月计算
  8. //加两年
  9. LocalDateTime ldt3 = ldt.plusYears(2);
  10. System.out.println(ldt3);
  11. //减两个月
  12. LocalDateTime ldt4 = ldt.minusMonths(2);
  13. System.out.println(ldt4);
  14. System.out.println("年:"+ldt.getYear());
  15. System.out.println("月:"+ldt.getMonth());
  16. System.out.println("月:"+ldt.getMonthValue());
  17. System.out.println("日:"+ldt.getDayOfMonth());
  18. System.out.println("日:"+ldt.getDayOfWeek());
  19. System.out.println("日:"+ldt.getDayOfYear());
  20. }
  21. //2. Instant 时间戳(以 Unix 元年: 1970年1月1日 00:00:00 到某个时间之间的毫秒值)
  22. @Test
  23. public void test2(){
  24. Instant ins1 = Instant.now();//默认获取 UTC 时区
  25. System.out.println(ins1);
  26. OffsetDateTime odt = ins1.atOffset(ZoneOffset.ofHours(8));
  27. System.out.println(odt);
  28. //转时间戳
  29. System.out.println(ins1.getEpochSecond());
  30. }
  31. //3. Druation: 计算两个“时间”之间的间隔
  32. //Period: 计算两个“日期”之间的间隔
  33. @Test
  34. public void test3(){
  35. Instant ins1 = Instant.now();
  36. try {
  37. Thread.sleep(1000);
  38. } catch (InterruptedException ignored) {}
  39. Instant ins2 = Instant.now();
  40. Duration btn = Duration.between(ins1, ins2);
  41. System.out.println(btn.getSeconds());//秒
  42. System.out.println(btn.toMillis());//毫秒
  43. System.out.println("----------------------------------------");
  44. LocalTime lt1 = LocalTime.now();
  45. try {
  46. Thread.sleep(1000);
  47. } catch (InterruptedException ignored) {}
  48. LocalTime lt2 = LocalTime.now();
  49. System.out.println(Duration.between(lt1, lt2).toMillis());
  50. System.out.println("----------------------------------------");
  51. LocalDate of = LocalDate.of(2020, 8, 20);
  52. LocalDate now = LocalDate.now();
  53. Period period = Period.between(of, now);
  54. System.out.println(period.getYears());
  55. System.out.println(period.getMonths());
  56. System.out.println(period.getDays());
  57. }
  58. //自定义时间格式化
  59. @Test
  60. public void test4() {
  61. DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  62. LocalDateTime ldt = LocalDateTime.now();
  63. System.out.println(ldt);
  64. System.out.println(dtf.format(ldt));//2019-09-26 23:11:53
  65. System.out.println("-------------------------------------------");
  66. //LocalDateTime总是表示本地日期和时间,要表示一个带时区的日期和时间,我们就需要
  67. ZonedDateTime
  68. ZonedDateTime zdt = ZonedDateTime.now();
  69. System.out.println(zdt);
  70. System.out.println(dtf.format(zdt));
  71. }
  72. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/393529
推荐阅读
相关标签
  

闽ICP备14008679号