0

我想测试转换为日历的字符串是现在之前还是之后。我不明白为什么这不起作用:

public final static SimpleDateFormat DATE_FORMAT_RESERVATION_HOUR = new SimpleDateFormat("HH:mm");    
String str = "14:00";

Calendar now = Calendar.getInstance();
Calendar selected = Calendar.getInstance();
//avoiding try/catch in this post
selected.set(Calendar.HOUR_OF_DAY, (int) DATE_FORMAT_RESERVATION_HOUR.parse(str).getTime());
// selected = now : 7352-05-18 00:49:33 (instead of 2013-06-17 14:00:00
Log.d("test", "after?" + selected.after(now));

我希望现在是“选定”,但在 str 中指定了小时。欢迎任何帮助!谢谢

4

1 回答 1

1

I don't understand why this is not working:

getTime():

Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This is not the value which you want to set the Calendar.HOUR_OF_DAY for the desired result.

  1. You can use the deprecated getHours() in your case :

    selected.set(Calendar.HOUR_OF_DAY, 
               (int) DATE_FORMAT_RESERVATION_HOUR.parse(str).getHours());
    

2. If the variable str will always be in that format , then you can also do this :

    selected.set(Calendar.HOUR_OF_DAY, Integer.parseInt(str.split(":")[0]));
于 2013-06-17T12:14:05.693 回答