本地时间与时间戳

LocalDateLocalTimeLocalDateTime 类的实例是不可变的对象,分别表示使用iso-8601历系统的日期、时间、日期和时间。它提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。

本地时间

  1. // LocalDate LocalTime LocalDateTime
  2. @Test
  3. public void test01(){
  4. // 获取当前日期和时间
  5. LocalDateTime ldt = LocalDateTime.now();
  6. System.out.println(ldt);
  7. // 自定义日期时间返回一个LocalDateTime实例
  8. LocalDateTime of = LocalDateTime.of(2015, 10, 19, 13, 22, 33);
  9. System.out.println(of);
  10. // 年份增加,返回一个新的实例
  11. LocalDateTime localDateTime = ldt.plusYears(10);
  12. System.out.println(localDateTime);
  13. // 年份减少,返回一个新的实例
  14. LocalDateTime localDateTime1 = ldt.minusYears(10);
  15. System.out.println(localDateTime1);
  16. // 获取年、月、日、时、分、秒
  17. System.out.println(ldt.getYear());
  18. System.out.println(ldt.getMonthValue());
  19. System.out.println(ldt.getDayOfMonth());
  20. System.out.println(ldt.getHour());
  21. System.out.println(ldt.getMinute());
  22. System.out.println(ldt.getSecond());
  23. }

时间戳

以Unix元年:1970年1月1日00:00:00到某个时间之间的毫秒值被称为时间戳。

  1. Instant

    1. @Test
    2. public void test02(){
    3. // 默认获取 UTC 时区的时间 UTC(世界协调时间)
    4. Instant now = Instant.now();
    5. System.out.println(now);
    6. // 设置偏移量的时间
    7. OffsetDateTime offsetDateTime = now.atOffset(ZoneOffset.ofHours(8));
    8. System.out.println(offsetDateTime);
    9. // 毫秒显示
    10. long l = now.toEpochMilli();
    11. System.out.println(l);
    12. // 设置从1970年1月1日00:00:00 在加上1秒开始计算
    13. Instant instant = Instant.ofEpochSecond(1);
    14. System.out.println(instant);
    15. }
  2. Duration:两个时间之间的间隔

    1. @Test
    2. public void test03() throws InterruptedException {
    3. // Duration:计算两个时间之间的间隔
    4. Instant now1 = Instant.now();
    5. Thread.sleep(1000);
    6. Instant now2 = Instant.now();
    7. Duration between = Duration.between(now1, now2);
    8. System.out.println(between.toMillis());
    9. }
    1. @Test
    2. public void test04() throws InterruptedException {
    3. LocalTime l1 = LocalTime.now();
    4. Thread.sleep(1000);
    5. LocalTime l2 = LocalTime.now();
    6. Duration between = Duration.between(l1, l2);
    7. System.out.println(between.toMillis());
    8. }
  3. Period:计算两个日期之间的间隔

    1. @Test
    2. public void test05(){
    3. LocalDate ld = LocalDate.of(2015,10,10);
    4. LocalDate ld2 = LocalDate.of(2020,12,20);
    5. Period between = Period.between(ld, ld2);
    6. System.out.println(between.getYears());// 相差年
    7. System.out.println(between.getMonths());// 相差月
    8. System.out.println(between.getDays());// 相差日
    9. }

    时间矫正器