【问题标题】:How to Compare datetime in Android如何在 Android 中比较日期时间
【发布时间】:2016-10-10 14:02:09
【问题描述】:

我有日期、date1(now) 和 date2,它们以 JSON 字符串形式返回,例如 2016-07-09 21:26:04

我想比较这两个日期

if(date1 < date2){

}

【问题讨论】:

    标签: java android json datetime compare


    【解决方案1】:

    这是在 Android 中比较两个 DateTime 对象的代码:

     public void onDateSelected(DateTime dateSelected) {
        DateTime currentDateTime = new DateTime(); 
    
        try{
            // You can use any format to compare by spliting the dateTime 
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
    
            String str1 = dateSelected.toString();
            Date selectedDate = formatter.parse(str1);
    
            String str2 = currentDateTime.toString();
            Date currentDate = formatter.parse(str2);
    
            if (selectedDate.compareTo(currentDate)<0)
            {
                System.out.println("current date is Greater than my selected date");
            }
            else
            {
                System.out.println("selected date is Greater than my current date"); 
            }
    
        }catch (ParseException e1){
            e1.printStackTrace();
        }
     }
    

    【讨论】:

      【解决方案2】:

      我会这样做:

      1. 将 in 解析为 Date 对象
      2. 比较那些

      示例:

       public static void main(String x[]) throws ParseException {
          String s1 = "2016-07-09 21:26:04";
          String s2 = "2006-07-09 21:26:04";
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          Date d1 = sdf.parse(s1);
          Date d2 = sdf.parse(s2);
          int compareResult = d1.compareTo(d2);
          if (compareResult > 0) {
              System.out.println(s1 + " is younger than " + s2);
          } else if (compareResult < 0) {
              System.out.println(s1 + " is younger than " + s2);
          } else {
              System.out.println(s1 + " is equals than " + s2);
          }
          }
      

      【讨论】:

        【解决方案3】:
        SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date today= new Date();
        
        try {
                if (today.before(sdf.forrmat(json_string_date))) {
                  // If start date is before end date.
                  // Do your piece of code
                 } 
            }catch (ParseException e) {
                e.printStackTrace();
            }
        

        【讨论】:

          猜你喜欢
          • 2021-09-20
          • 2011-01-21
          • 2021-06-06
          • 1970-01-01
          • 1970-01-01
          • 2014-03-20
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          相关资源
          最近更新 更多