当前位置: 移动技术网 > IT编程>开发语言>Java > 使用java的Calendar对象获得当前日期

使用java的Calendar对象获得当前日期

2019年07月22日  | 移动技术网IT编程  | 我要评论

思路:

先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期

/**
   * @param flag true:开始日期;false:结束日期
   * @return
   */
  public static string getlastquartertime(boolean flag){
    simpledateformat shortsdf = new simpledateformat("yyyy-mm-dd");
    simpledateformat longsdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
     
    string resultdate="";
    date now = null;
    try {
      calendar calendar = calendar.getinstance();
      int currentmonth = calendar.get(calendar.month) + 1;
      //true:开始日期;false:结束日期
      if(flag){
        if (currentmonth >= 1 && currentmonth <= 3)
          calendar.set(calendar.month, 0);
        else if (currentmonth >= 4 && currentmonth <= 6)
          calendar.set(calendar.month, 3);
        else if (currentmonth >= 7 && currentmonth <= 9)
          calendar.set(calendar.month, 6);
        else if (currentmonth >= 10 && currentmonth <= 12)
          calendar.set(calendar.month, 9);
        calendar.set(calendar.date, 1);
         
        now = longsdf.parse(shortsdf.format(calendar.gettime()) + " 00:00:00");
      }else{
        if (currentmonth >= 1 && currentmonth <= 3) {
          calendar.set(calendar.month, 2);
          calendar.set(calendar.date, 31);
        } else if (currentmonth >= 4 && currentmonth <= 6) {
          calendar.set(calendar.month, 5);
          calendar.set(calendar.date, 30);
        } else if (currentmonth >= 7 && currentmonth <= 9) {
          calendar.set(calendar.month, 8);
          calendar.set(calendar.date, 30);
        } else if (currentmonth >= 10 && currentmonth <= 12) {
          calendar.set(calendar.month, 11);
          calendar.set(calendar.date, 31);
        }
        now = longsdf.parse(shortsdf.format(calendar.gettime()) + " 23:59:59");
      }
      calendar.settime(now);// 设置日期
      calendar.add(calendar.month, -3);
      resultdate = longsdf.format(calendar.gettime());
       
    } catch (exception e) {
      ;
    }
    return resultdate;
  }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网