日期工具类


import cn.hutool.json.JSONUtil;

import java.time.LocalDate;
import java.time.Year;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;

public class DateUtil {

/**
* 获取最近 n 日日期数据
* @param n
* @param containCurDay
* @return
*/
public static String[] getLastDays(int n, boolean containCurDay) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate currentDate = LocalDate.now();// 获取当前日期
String[] dates = new String[n];
int temp = n;
if(containCurDay){
temp = (n - 1);
}
for (int i = 0; i < n; i++) {
LocalDate localDate = LocalDate.from(currentDate).minusDays(temp-i);
dates[i] = localDate.format(formatter);
}
return dates;
}

/**
* 获取最近 n 月日期数据
* @param n
* @param containCurMonth 是否包含当前月
* @return ["2024-07","2024-08","2024-09"]
*/
public static String[] getLastMonths(int n, boolean containCurMonth) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
LocalDate currentDate = LocalDate.now();// 获取当前日期
String[] months = new String[n];
int temp = n;
if(containCurMonth){
temp = (n - 1);
}
for (int i = 0; i < n; i++) {
YearMonth yearMonth = YearMonth.from(currentDate).minusMonths(temp-i);
months[i] = yearMonth.format(formatter);
}
return months;
}

/**
* 获取最近 n 年日期数据
* @param n
* @param containCurYear
* @return ["2022","2023","2024"]
*/
public static String[] getLastYears(int n, boolean containCurYear) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
LocalDate currentDate = LocalDate.now();// 获取当前日期
String[] years = new String[n];
int temp = n;
if(containCurYear){
temp = (n - 1);
}
for (int i = 0; i < n; i++) {
Year year = Year.from(currentDate).minusYears(temp-i);
years[i] = year.format(formatter);
}
return years;
}

public static void main(String[] args) {

// 获取最近30天日期数据
String[] last30Days = DateUtil.getLastDays(30, true);
System.out.println(JSONUtil.toJsonStr(last30Days));

// 获取最近12个月数据
String[] last12Months = DateUtil.getLastMonths(2, true);
System.out.println(JSONUtil.toJsonStr(last12Months));

// 获取最近3年日期数据
String[] last3Years = DateUtil.getLastYears(3, true);
System.out.println(JSONUtil.toJsonStr(last3Years));

}

}
 

 

posted @ 2024-09-04 09:12  java小天地  阅读(12)  评论(0)    收藏  举报