1. 程式人生 > >判斷日期是不是今天/昨天/前天

判斷日期是不是今天/昨天/前天

/**
      * 格式化時間
      *
      * @param time
      * @return - 1:昨天;-2:前天;0:今天; -8:預設時間;-7:傳入的引數不對
      */
     private int formatDateTime(String time) {
           SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm" );
           if (time == null || "".equals( time)) {
               return -7;
          }
          Date date = null;
           try {
               date = format.parse( time);
          } catch (ParseException e ) {
               e.printStackTrace();
          }

          Calendar current = Calendar. getInstance();

          Calendar today = Calendar. getInstance(); // 今天

           today.set(Calendar. YEAR, current.get(Calendar.YEAR));
           today.set(Calendar. MONTH, current.get(Calendar.MONTH));
           today.set(Calendar. DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
           // Calendar.HOUR——12小時制的小時數 Calendar.HOUR_OF_DAY——24小時制的小時數
           today.set(Calendar. HOUR_OF_DAY, 0);
           today.set(Calendar. MINUTE, 0);
           today.set(Calendar. SECOND, 0);

          Calendar yesterday = Calendar.getInstance(); // 昨天
           yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
           yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
           yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
           yesterday.set(Calendar.HOUR_OF_DAY, 0);
           yesterday.set(Calendar.MINUTE, 0);
           yesterday.set(Calendar.SECOND, 0);

          Calendar yesterday2 = Calendar.getInstance(); // 昨天
           yesterday2.set(Calendar.YEAR, current.get(Calendar.YEAR));
           yesterday2.set(Calendar.MONTH, current.get(Calendar.MONTH));
           yesterday2.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 2);
           yesterday2.set(Calendar.HOUR_OF_DAY, 0);
           yesterday2.set(Calendar.MINUTE, 0);
           yesterday2.set(Calendar.SECOND, 0);

           current.setTime( date);

           if (current .after(today )) {
               return 0;
          } else if (current .before(today ) && current.after(yesterday )) {
               return -1;
          } else if (current .before(yesterday ) && current.after(yesterday2 )) {
               return -2;
          } else {
               return -8;
          }
     }