• Java获取给定月份的前N个月份和前N个季度


    描述:

    项目开发过程中,遇到这样一个需求,即:给定某一月份,得到该月份前面的几个月份以及前面的几个季度。例如:给定2023-09,获取该月份前面的前3个月,即2023-08、2023-07、2023-06,以及该月份的前3个季度,即2023-06、2023-03、2022-12。

    代码:

    1. import java.text.SimpleDateFormat;
    2. import java.util.ArrayList;
    3. import java.util.Calendar;
    4. import java.util.Date;
    5. import java.util.List;
    6. public class Test {
    7. public static void main(String[] args) {
    8. System.out.println(getMonthDate("2023-2", 5));
    9. System.out.println(getQuarterDate("2023-2", 4));
    10. }
    11. /**
    12. * 获取给定日期的前Num个月份
    13. * @param strDate 日期
    14. * @param num 个数
    15. * @return
    16. */
    17. public static List getMonthDate(String strDate, int num){
    18. List monthList = new ArrayList<>();
    19. for(int i=0; i < num; i++){
    20. monthList.add(generatePreDate(strDate, i));
    21. }
    22. return monthList;
    23. }
    24. /**
    25. * 获取给定日期的前Num个季度
    26. * @param strDate 日期
    27. * @param num 个数
    28. * @return
    29. */
    30. public static List getQuarterDate(String strDate, int num){
    31. strDate = judgeQuarter(strDate);
    32. List quarterList = new ArrayList<>();
    33. for (int i = 0; i < num; i++) {
    34. quarterList.add(generatePreDate(strDate, i * 3));
    35. }
    36. return quarterList;
    37. }
    38. /**
    39. * 判断月份属于哪个季度
    40. * @param date
    41. * @return
    42. */
    43. public static String judgeQuarter(String date){
    44. String[] strs = date.split("-");
    45. String result = strs[0] + "-";
    46. int month = Integer.parseInt(strs[1]);
    47. if(month >= 1 && month <= 3){
    48. result += "03";
    49. }
    50. if(month >= 4 && month <= 6){
    51. result += "06";
    52. }
    53. if(month >= 7 && month <= 9){
    54. result += "09";
    55. }
    56. if(month >= 10 && month <= 12){
    57. result += "12";
    58. }
    59. return result;
    60. }
    61. public static String generatePreDate(String strDate, int num){
    62. String stringDate="";
    63. try {
    64. SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
    65. Date month=formatter.parse(strDate);
    66. Calendar calendar = Calendar.getInstance();//得到Calendar实例
    67. calendar.setTime(month);
    68. calendar.add(Calendar.MONTH, -num);
    69. Date starDate = calendar.getTime();//得到时间赋给Data
    70. stringDate = formatter.format(starDate);//使用格式化Data
    71. return stringDate;
    72. }catch (Exception e){
    73. e.printStackTrace();
    74. return stringDate;
    75. }
    76. }
    77. }

    实现结果:

  • 相关阅读:
    传感器融合带来多重好处
    spring源码1--自定义Autowired实现
    Linux - tar (tape archive)
    Linux系列之比较命令
    设计模式之(8)——代理模式
    Linux 性能分析命令详解
    灰度级形态学 - 顶帽变换和底帽变换
    【考研英语语法】祈使句
    第1章 人工智能的基础概念与应用导论
    基于CNN的图片识别
  • 原文地址:https://blog.csdn.net/weixin_47382783/article/details/133281640