Get the current date using Java's Calendar object

  • 2020-04-01 03:58:58
  • OfStack

Ideas:

Get the start and end dates of the current quarter, and move forward 3 months from the current date to the start and end dates of the previous quarter



  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: start date; False: end date
      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);//Set the date
      calendar.add(Calendar.MONTH, -3);
      resultDate = longSdf.format(calendar.getTime());
       
    } catch (Exception e) {
      ;
    }
    return resultDate;
  }


Related articles: