Вопрос

I want to compare two times like 12AM and 1AM. I have made following function to do this

public int timeValidation(){
    String stTime=btn_srt_time.getText().toString();
    String endtime=btn_end_time.getText().toString();

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("kk:mm");

     Date date1;
     Date date2;
    try {

        date1 = simpleDateFormat.parse(stTime);         
        System.out.println("================== date1=================="+date1);

        date2 = simpleDateFormat.parse(endtime);
        System.out.println("===========> date 2 ==============>"+date2);            

        return date1.compareTo(date2);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return 0;

 }

It gives me right answer when comparison is between 12:00AM and 12:45AM. But when I am comparing 12:00AM and 1:00AM it says 1:00AM is before 12:00AM pls help...

Это было полезно?

Решение

use yyyy-MM-dd hh:mm:ss a.

HH will be the hour in day (0-23) whereas hh will be the hour in AM/PM (1-12). Thus with your date format 02:30:00 will be parsed as just that instead of being converted to the PM version (which in hour of day would be 14:30:00). for more reference a look at this

Другие советы

Date time1, time2; 
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");

Calendar cal1 = Calendar.getInstance();
// 12:00 AM
cal1.set(0, 0, 0, 00, 00);

Calendar cal2 = Calendar.getInstance();
// 01:00 AM
cal2.set(0, 0, 0, 01, 00);

try {
            time1 = sdf.parse((String) DateFormat.format("hh:mm aaa", cal1));
            time2 = sdf.parse((String) DateFormat.format("hh:mm aaa", cal2));
        }catch (Exception e){}

if(time2.after(time1)){
 //time2 is greater
}else if(time2.before(time1)){
//time1 is greater
}else{
//both time is equal
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top