如何比较Java中的原始时间到现在?

时间:2011-05-17 13:28:55

标签: java

  

可能重复:
  How do I compare a raw time in Java?

例如假设我有

String endTime = "16:30:45";

我如何确定现在是否在此之前?我试过了

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss")
Date date = sdf.parse(endTime);

然而,日期是1970年,因此比较失败

2 个答案:

答案 0 :(得分:7)

你可以随时做反过来:

"16:30:45".compareTo(new SimpleDateFormat("HH:mm:ss").format(new Date()))

答案 1 :(得分:2)

//Parse the time from String using SimpleDateFormat and set it to cal, reset other fields

    Calendar cal = Calendar.getInstance();
    cal.setTime(parsedTimeinDate);
    cal.set(Calendar.MONTH,0);
    cal.set(Calendar.YEAR,2000);
    cal.set(Calendar.DATE,1);    
//reset other fields for now calendar those aren't related to time
    Calendar calNow = Calendar.getInstance();
    calNow .set(Calendar.MONTH,0);
    calNow .set(Calendar.YEAR,2000);
    calNow .set(Calendar.DATE,1);

//determine 
    cal.before(calNow);