Get the latest date by day, week, or month

Recently I came across a requirement to calculate the data statistics of the recent time period by day, week, and month. I
wrote it in a hurry, so the method used and the logic of writing will be a bit confusing. I apologize for it. I will record it first. If there is any more A good method will be updated below
1. Get the date of each day of the previous week

// 按日统计
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
for (int i = 0; i < 7; i++) {
    
    
    Date date = DateUtils.addDays(new Date(), -i);
    String formatDate = format.format(date);
    System.out.println(formatDate);
}

result:
Insert image description here

2. Get the start and end dates of the last four weeks

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
LocalDate date = LocalDate.now();
if (date.getDayOfWeek().getValue() == 0){
    
    
    date = date.minus(1, ChronoUnit.DAYS);
}

// 本周一日期
date = date.minus(date.getDayOfWeek().getValue() - 1, ChronoUnit.DAYS);
LocalDate localSunday = date.minus(date.getDayOfWeek().getValue() - 7, ChronoUnit.DAYS);

System.out.println(date + "****" + localSunday);

for (int i = 0; i < 3; i++) {
    
    
    date = date.minus(date.getDayOfWeek().getValue() + 6, ChronoUnit.DAYS);
    LocalDate lastSunday = date.minus(date.getDayOfWeek().getValue() - 7, ChronoUnit.DAYS);

    System.out.println(date + "****" + lastSunday);
}

Result:
Insert image description here
3. Get the start and end dates of the last six months

// 按月统计
LocalDate date = LocalDate.now();
LocalDate firstDate = date.withDayOfMonth(1);
// 计算本月
LocalDate nextFirstDay = firstDate.minus(-1, ChronoUnit.MONTHS);
System.out.println(firstDate + "****" + nextFirstDay);

for (int i = 0; i < 5; i++) {
    
    
    firstDate = firstDate.minus(1,ChronoUnit.MONTHS);
    LocalDate endDate = firstDate.minus(-1,ChronoUnit.MONTHS);
    System.out.println(firstDate + "****" + endDate);
}

Insert image description here
The last one is a bit ridiculous... I originally wanted to get the last day of this month, but then I wanted to get the first day of the second month. Finally, when searching by date in the database, it was directly smaller than the first day of the second month ( 2022-12-01 00:00:00) will do...

Guess you like

Origin blog.csdn.net/s990420/article/details/128053681