1. 根据当前时间获取指定N个月之前的月份第一天。

      /**
    * 根据当前日期,获取当前月前5个月的开始日期
    * 当前日期为2021-10-5号 返回结果是 2021-05-01 00:00:00
    *
    * @param earlyMonth 提前几个月时间 earlyMonth = 5
    * @return 2021-05-01 00:00:00
    */
      private String getStartDateTime(Integer earlyMonth) {
    
       LocalDateTime date = LocalDateTime.now().minusMonths(earlyMonth);
    
       LocalDateTime firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
    
       String firstDayStr = firstDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
       log.info("firstDayStr:{}", firstDayStr);
    
       return firstDayStr;
      }
  2. 获取当前日期开始前N个月的第一天的零时零分零秒开始,这个写法比上面的更优雅
@Test
    public void test1() {
        Integer earlyMonth = 5;
        LocalDateTime date = LocalDateTime.now()
                .minusMonths(earlyMonth)
                .withDayOfMonth(1)
                .withHour(0)
                .withMinute(0)
                .withSecond(0)
                .withNano(0);

        System.out.println("firstDayStr:" + date);
        // 输出结果 firstDayStr:2021-12-01T00:00
    }
  1. localDateTime与Date互相转换
  2. localDateTime与Date比较大小
  3. date与string互相转换
@Test
    public void test3() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        String dateStr = "2022-07-12";
        try {
            // string转日期
            Date date = df.parse(dateStr);

            // 日期转string
            System.out.println(df.format(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

求平安
15 声望0 粉丝

家人平平安安。