Android比较日期时间

时间:2010-02-27 16:58:33

标签: android datetime

我正在尝试比较两个日期时间,但我无法让它工作。

    public void time () {
        Calendar c11 = Calendar.getInstance ();
        c11.add(Calendar.DAY_OF_YEAR, 0);
        c11.set(Calendar.HOUR_OF_DAY, 9);
        c11.set(Calendar.MINUTE, 0 );
        c11.set(Calendar.SECOND, 0);

        Calendar c12 = Calendar.getInstance ();
        c12.add(Calendar.DAY_OF_YEAR, 0);
        c12.set(Calendar.HOUR_OF_DAY, 9);
        c12.set(Calendar.MINUTE, 0 );
        c12.set(Calendar.SECOND, 0);

        c11.getTime();
        c12.getTime();
        boolean k = c11.equals(c12);
        if (k==true)
        {
            Toast.makeText(
              getContext(),
              "Wow these two times are the same!",
              Toast.LENGTH_LONG).show();
        }
    }
    }

2 个答案:

答案 0 :(得分:3)

  1. 2个时间值的毫秒数不同,因此相等比较将返回false。

  2. 为什么要在两个日历实例中添加0天?这没有任何作用。

答案 1 :(得分:1)

 public void onDateSelected(DateTime dateSelected) {
    DateTime currentDateTime = new DateTime(); 

    try{
        /* If you want to compare only date from DateTime object then,
           you can use "yyyy-MM-dd" format and split the string from T like: 
           dateSelected.toString().split("T") and use str1[0] to parse */  

        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");
        }

    }catch (ParseException e1){
        e1.printStackTrace();
    }
 }