Java时间操作

一、新时间日期Api

1.重要对象介绍

LocalDate: 表示没有时区的日期, LocalDate是不可变并且线程安全的
LocalTime: 表示没有时区的时间, LocalTime是不可变并且线程安全的
LocalDateTime: 表示没有时区的日期时间, LocalDateTime是不可变并且线程安全的
Instant: 用来表示时间线上的一个点(瞬时)
ZoneId: 时区ID,用来确定Instant和LocalDateTime互相转换的规则
Period: 用于计算两个“日期”间隔
Duration: 用秒和纳秒表示时间的数量(长短),用于计算两个日期的“时间”间隔
Clock: 用于访问当前时刻、日期、时间,用到时区

2.当前时间

LocalDate localDate = LocalDate.now();
LocalTime localtime = LocalTime.now();
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDate);
System.out.println(localtime);
System.out.println(localDateTime);

// 输出结果
2022-01-25
20:10:16.825
2022-01-25T20:10:16.825

3.指定日期/时间

LocalDate localDate = LocalDate.of(2022, 1, 25);
LocalTime localtime = LocalTime.of(20, 10, 16);
LocalDateTime localDateTime = LocalDateTime.of(2022, 1, 25, 20, 10, 16);
LocalDateTime localDateTime1 = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
System.out.println(localDate);
System.out.println(localtime);
System.out.println(localDateTime);
System.out.println(localDateTime1);

// 输出结果
2022-01-25
20:10:16
2022-01-25T20:10:16
2022-01-25T00:00

4.日期时间的加减

日期的加plus和减minus类似,以plus为例:

LocalDateTime localDateTime = LocalDateTime.now();
LocalDateTime plusYearsResult = localDateTime.plusYears(1L);
LocalDateTime plusMonthsResult = localDateTime.plusMonths(1L);
LocalDateTime plusDaysResult = localDateTime.plusDays(1L);
LocalDateTime plusHoursResult = localDateTime.plusHours(1L);
LocalDateTime plusMinutesResult = localDateTime.plusMinutes(1L);
LocalDateTime plusSecondsResult = localDateTime.plusSeconds(1L);

System.out.println("当前时间是 : " + localDateTime + "\n"
        + "当前时间加1年后为 : " + plusYearsResult + "\n"
        + "当前时间加1个月后为 : " + plusMonthsResult + "\n"
        + "当前时间加1日后为 : " + plusDaysResult + "\n"
        + "当前时间加1小时后为 : " + plusHoursResult + "\n"
        + "当前时间加1分钟后为 : " + plusMinutesResult + "\n"
        + "当前时间加1秒后为 : " + plusSecondsResult + "\n"
);

System.out.println();
//也可以以另一种方式来相加减日期,即plus(long amountToAdd, TemporalUnit unit) 参数1 : 相加的数量, 参数2 : 相加的单位
LocalDateTime plusYears = localDateTime.plus(1, ChronoUnit.YEARS);
LocalDateTime plusMonths = localDateTime.plus(1, ChronoUnit.MONTHS);
LocalDateTime plusDays = localDateTime.plus(1, ChronoUnit.DAYS);

System.out.println("now : " + localDateTime + "\n"
        + "当前时间加1年 plusYears : " + plusYears + "\n"
        + "当前时间加1个月 plusMonths: " + plusMonths + "\n"
        + "当前时间加1天 plusDays :" + plusDays + "\n"
);

// 输出结果
当前时间是 : 2022-01-25T20:28:36.179
当前时间加1年后为 : 2023-01-25T20:28:36.179
当前时间加1个月后为 : 2022-02-25T20:28:36.179
当前时间加1日后为 : 2022-01-26T20:28:36.179
当前时间加1小时后为 : 2022-01-25T21:28:36.179
当前时间加1分钟后为 : 2022-01-25T20:29:36.179
当前时间加1秒后为 : 2022-01-25T20:28:37.179


当前时间 : 2022-01-25T20:28:36.179
当前时间加1年 plusYears : 2023-01-25T20:28:36.179
当前时间加1个月 plusMonths: 2022-02-25T20:28:36.179
当前时间加1天 plusDays :2022-01-26T20:28:36.179

5.修改年、月、日等为指定的值

LocalDate localDate = LocalDate.now();
  // 指定年
  LocalDate withYearResult = localDate.withYear(2023);
  // 指定月
  LocalDate withMonthResult = localDate.withMonth(2);
  // 指定本年当中的第几天
  LocalDate withDayOfYearResult = localDate.withDayOfYear(5);
  // 指定本月当中的第几天
  LocalDate withDayOfMonthResult = localDate.withDayOfMonth(5);
  // 本年的第一天
  LocalDate firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear());
  // 本月的最后一天
  LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());

  System.out.println("当前时间是 : " + localDate + "\n"
          + "指定年 : " + withYearResult + "\n"
          + "指定月 : " + withMonthResult + "\n"
          + "指定本年当中的第5天 : " + withDayOfYearResult + "\n"
          + "指定本月当中的第5天 : " + withDayOfMonthResult + "\n"
          + "指定本年第1天 : " + firstDayOfYear + "\n"
          + "指定本月最后1天 : " + lastDayOfMonth + "\n"
  );

// 输出结果
当前时间是 : 2022-01-25
指定年 : 2023-01-25
指定月 : 2022-02-25
指定本年当中的第5天 : 2022-01-05
指定本月当中的第5天 : 2022-01-05
指定本年第1天 : 2022-01-01
指定本月最后1天 : 2022-01-31

6.获取日期的年月日周时分秒

LocalDateTime localDateTime = LocalDateTime.now();
int dayOfYear = localDateTime.getDayOfYear();
int dayOfMonth = localDateTime.getDayOfMonth();
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println("今天是" + localDateTime + "\n"
        + "本年当中第" + dayOfYear + "天" + "\n"
        + "本月当中第" + dayOfMonth + "天" + "\n"
        + "本周中星期" + dayOfWeek.getValue() + "-即" + dayOfWeek + "\n");

// 获取当天时间的年月日时分秒
int year = localDateTime.getYear();
Month month = localDateTime.getMonth();
int day = localDateTime.getDayOfMonth();
int hour = localDateTime.getHour();
int minute = localDateTime.getMinute();
int second = localDateTime.getSecond();
System.out.println("今天是" + localDateTime + "\n"
        + "年 : " + year + "\n"
        + "月 : " + month.getValue() + "-即 "+ month + "\n"
        + "日 : " + day + "\n"
        + "时 : " + hour + "\n"
        + "分 : " + minute + "\n"
        + "秒 : " + second + "\n"
);

// 输出结果
今天是2022-01-26T10:27:38.344
本年当中第26天
本月当中第26天
本周中星期3-即WEDNESDAY

今天是2022-01-26T10:27:38.344
年 : 2022
月 : 1-即 JANUARY
日 : 26
时 : 10
分 : 27
秒 : 38

7.计算时间、日期间隔

Period:用于计算两个“日期”间隔
Duration:用于计算两个“时间”间隔

// 计算两个日期的日期间隔-年月日(注:不是单纯的年月日对应的数字相减,而是会先算出具体差多少天,在折算成相差几年几月几日)
LocalDate date1 = LocalDate.of(2022, 1, 26);
LocalDate date2 = LocalDate.of(2023, 1, 1);
// date2-date1,注意负数问题
Period period = Period.between(date1, date2);
System.out.println("相差年数 : " + period.getYears());
System.out.println("相差月数 : " + period.getMonths());
System.out.println("相差日数 : " + period.getDays());  // 此处有坑,相差天数
System.out.println(date1.until(date2, ChronoUnit.DAYS));   // 算间隔用这个

// 计算两个时间的间隔
System.out.println("-------------------------------");
LocalDateTime date3 = LocalDateTime.now();
LocalDateTime date4 = LocalDateTime.of(2023, 2, 1, 0, 0, 0);
Duration duration = Duration.between(date3, date4);
System.out.println(date3 + " 与 " + date4 + " 间隔  " + "\n"
        + "天 :" + duration.toDays() + "\n"
        + "时 :" + duration.toHours() + "\n"
        + "分 :" + duration.toMinutes() + "\n"
        + "毫秒 :" + duration.toMillis() + "\n"
        + "纳秒 :" + duration.toNanos() + "\n"
);

// 输出结果
相差年数 : 0
相差月数 : 11
相差日数 : 6
340
-------------------------------
2022-01-26T10:51:33.680 与 2023-02-01T00:00 间隔  
天 :370
时 :8893
分 :533588
毫秒 :32015306320
纳秒 :32015306320000000

8.格式化/解析时间

// 自定义格式化
DateTimeFormatter dateTimeFormatter =   DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
System.out.println(localDate.format(DateTimeFormatter.BASIC_ISO_DATE));
System.out.println(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
System.out.println(localDate.format(dateTimeFormatter));

System.out.println("-------------------");
// 解析时间
System.out.println(LocalDate.parse("20220126", DateTimeFormatter.BASIC_ISO_DATE));
System.out.println(LocalDate.parse("2022-01-27", DateTimeFormatter.ISO_LOCAL_DATE));

// 输出结果
20220126
2022-01-26
2022/01/26
-------------------
2022-01-26
2022-01-27

9.时间戳/Date/LocalDateTime的转换

LocalDate/LocalDateTime和时间戳转换(Instant中介)

        // LocalDateTime转时间戳
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDateTime.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        System.out.println(localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());

        // LocalDate转时间戳
        LocalDate localDate = LocalDate.now();
        System.out.println(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().getEpochSecond());
        System.out.println(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());

        // 时间戳转LocalDate/LocalDateTime
        System.out.println(Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneId.systemDefault()).toLocalDate());
        System.out.println(Instant.ofEpochMilli(System.currentTimeMillis()).atZone(ZoneId.systemDefault()).toLocalDateTime());

LocalDate/LocalDateTime和Date转换(Instant中介)

        // Date转LocalDate/LocalDateTime
        LocalDate localDate = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDateTime localDateTime = new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // LocalDate/LocalDateTime转Date
        Date localDateToDate = Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant());
        Date date = Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant());

10.其他方法

LocalDate localDate1 = LocalDate.now();
 LocalDate localDate2 = LocalDate.of(2022, 2, 1);
 // 判断时间先后
 System.out.println(localDate1.isBefore(localDate2));

 // 判断是否是闰年
 System.out.println(LocalDate.now().isLeapYear());

二、Q&A

1.为什么不使用Date

  • 不进行格式化,打印的时间可读性差
  • SimpleDateFormat线程不安全
  • 操作时间不方便
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的LocalDate类是用来表示日期的类,与java.util.Date类略有不同,它只包含日期,没有时间。可以使用LocalDate类进行各种日期操作。例如,可以使用以下方法获取年份、月份、日期、星期几等信息: - `LocalDate.now().getYear()`:获取当前年份。 - `LocalDate.now().getMonthValue()`:获取当前月份的数值表示,从1开始。 - `LocalDate.now().getMonth()`:获取当前月份的英文表示。 - `LocalDate.now().getDayOfMonth()`:获取当前日期,从1开始。 - `LocalDate.now().getDayOfYear()`:获取当前日期在当年中的第几天,从1开始。 - `LocalDate.now().getDayOfWeek()`:获取当前星期几。 - `LocalDate.now().lengthOfYear()`:获取当年的天数。 - `LocalDate.now().lengthOfMonth()`:获取当月的天数。 - `LocalDate.now().toEpochDay()`:获取当前日期与时间纪元(1970年1月1日)相差的天数,负数表示在时间纪元之前多少天。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Java8时间LocalDate常用操作](https://blog.csdn.net/weixin_42130889/article/details/114524861)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [Java LocalDate](https://blog.csdn.net/qq_43308246/article/details/126142689)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值