根据当前时间获取指定N个月前一个月的第一天。/***根据当前日期,获取当月前5个月的开始日期*当前日期为2021-10-5,返回结果为2021-05-0100:00:00**@paramearlyMonth提前几个月时间earlyMonth=5*@return2021-05-0100:00:00*/privateStringgetStartDateTime(IntegerearlyMonth){LocalDateTimedate=LocalDateTime.now().minusMonths(earlyMonth);LocalDateTimefirstDay=date.with(TemporalAdjusters.firstDayOfMonth());StringfirstDayStr=firstDay.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));log.info("firstDayStr:{}",firstDayStr);返回第一天;开始于每月第一天的0:00:00:00:00:00:00,比上面的要优雅@Testpublicvoidtest1(){IntegerearlyMonth=5;LocalDateTime日期=LocalDateTime.now().minusMonths(earlyMonth).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);System.out.println("firstDayStr:"+date);//输出结果firstDayStr:2021-12-01T00:00}LocalDateTime和Date相互转换LocalDateTime和Date比较,日期和字符串相互转换@Testpublicvoidtest3(){DateFormatdf=newSimpleDateFormat("yyyy-MM-dd");StringdateStr="2022-07-12";try{//将字符串转换为日期Datedate=df.parse(dateStr);//将日期转换为字符串System.out.println(df.format(date));}赶上(ParseExceptione){e。打印堆栈跟踪();}}
