描述:
在项目开发过程中,遇到这样一个需求,即:给定某一月份,得到该月份前面的几个月份以及前面的几个季度。例如:给定2023-09,获取该月份前面的前3个月,即2023-08、2023-07、2023-06,以及该月份的前3个季度,即2023-06、2023-03、2022-12。
代码:
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.List;
-
- public class Test {
- public static void main(String[] args) {
- System.out.println(getMonthDate("2023-2", 5));
- System.out.println(getQuarterDate("2023-2", 4));
-
- }
-
- /**
- * 获取给定日期的前Num个月份
- * @param strDate 日期
- * @param num 个数
- * @return
- */
- public static List
getMonthDate(String strDate, int num){ - List
monthList = new ArrayList<>(); - for(int i=0; i < num; i++){
- monthList.add(generatePreDate(strDate, i));
- }
- return monthList;
- }
- /**
- * 获取给定日期的前Num个季度
- * @param strDate 日期
- * @param num 个数
- * @return
- */
- public static List
getQuarterDate(String strDate, int num){ - strDate = judgeQuarter(strDate);
- List
quarterList = new ArrayList<>(); - for (int i = 0; i < num; i++) {
- quarterList.add(generatePreDate(strDate, i * 3));
- }
- return quarterList;
- }
-
- /**
- * 判断月份属于哪个季度
- * @param date
- * @return
- */
- public static String judgeQuarter(String date){
- String[] strs = date.split("-");
- String result = strs[0] + "-";
- int month = Integer.parseInt(strs[1]);
- if(month >= 1 && month <= 3){
- result += "03";
- }
- if(month >= 4 && month <= 6){
- result += "06";
- }
- if(month >= 7 && month <= 9){
- result += "09";
- }
- if(month >= 10 && month <= 12){
- result += "12";
- }
- return result;
- }
-
-
- public static String generatePreDate(String strDate, int num){
- String stringDate="";
- try {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
- Date month=formatter.parse(strDate);
- Calendar calendar = Calendar.getInstance();//得到Calendar实例
- calendar.setTime(month);
- calendar.add(Calendar.MONTH, -num);
- Date starDate = calendar.getTime();//得到时间赋给Data
- stringDate = formatter.format(starDate);//使用格式化Data
- return stringDate;
- }catch (Exception e){
- e.printStackTrace();
- return stringDate;
- }
- }
- }
实现结果:
