Greg
Greg

Reputation: 709

Assign a specific hour to a Calendar

I want to test if a string converted to Calendar is before or after now. I don't understand why this is not working:

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

I would like "selected" to be now, but with the hour specified in str. Any help welcomed! Thanks

Upvotes: 0

Views: 79

Answers (1)

AllTooSir
AllTooSir

Reputation: 49402

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]));

Upvotes: 1

Related Questions