Android compare date and time

I am trying to compare two times, but I cannot get it to work.

    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();
        }
    }
    }
+3
source share
2 answers
  • Milliseconds of two time values ​​are different, so a comparison of equalities will return false.

  • Why are you adding 0 days to both calendar instances? It does nothing.

+3
source
 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();
    }
 }
+1
source

Source: https://habr.com/ru/post/1734692/


All Articles