欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-05 14:04:48
思路: 先获得当前季度的开始和结束日期,在当前日期的基础上往前推3个月即上个季度的开始和结束日期 /** * @param flag true:开始日期...

思路:

先获得当前季度的开始和结束日期,在当前日期的基础上往前推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;
  }