在大数据工作中遇到的一个统计问题,选择日期的起期或者是止期,可能是年,月,日,获取该时间段中的年,月,日的统计数据。首先就要去拿到时间段的集合,可能是年,可能是月,也可能是日,直接上代码
public static void main(String[] args) {
System.out.println(getTwoDaysDayDes("2023-01-01","2023-04-15"));
}
public static List<String> getTwoDaysDayDes(String startDate, String endDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<String> dateList = new ArrayList<String>();
try {
Date dateOne = sdf.parse(startDate);
Date dateTwo = sdf.parse(endDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOne);
dateList.add(startDate);
while (dateTwo.after(calendar.getTime())) {
calendar.add(Calendar.DATE, 1);
dateList.add(sdf.format(calendar.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
return dateList;
}
以上是获取日的List集合,若是要年或者月,把对应的日期格式改为‘yyyy’ 或者’yyyy-MM’,Calendar.DATE改为YEAR或者MONTH即可
如果是需要数据库获取的话,PGsql有一套方法
SELECT
to_char( T, ‘yyyy’ ) AS wmonth
FROM
generate_series ( ‘2022-01-01’ :: DATE, ‘2022-12-31’ :: DATE, ‘1 year’ :: INTERVAL ) AS T;
SELECT
to_char( T, ‘yyyy-MM’ ) AS wmonth
FROM
generate_series ( ‘2022-01-01’ :: DATE, ‘2022-12-31’ :: DATE, ‘1 month’ :: INTERVAL ) AS T;
SELECT
to_char( T, ‘yyyy-MM-dd’ ) AS wmonth
FROM
generate_series ( ‘2022-01-01’ :: DATE, ‘2022-12-31’ :: DATE, ‘1 day’ :: INTERVAL ) AS T;