CruelIO
CruelIO

Reputation: 18624

Parsing time to calendar

I would like to set the timepart of a calendar. Here is what I'm doing

Calendar calNow = Calendar.getInstance();
Calendar endWait = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date d1 = null;
try {
   d1 = sdf.parse("14:45");
}catch(ParseException ex){
    logger.error("Error parsing time");
}
 endWait.setTime(d1);
Date waitTo = endWait.getTime();   
Date now = calNow.getTime();

The "now" variable is correct date and time, however the waitTo was expected to be the date of today and time 14:45, but is tomorrow at 02:45.

Upvotes: 1

Views: 88

Answers (2)

Conffusion
Conffusion

Reputation: 4475

Calendar.setTime() will use the date and time information of the passed Date instance. To only update the hours and minutes of the waitTo you can:

    Calendar tmpCal=Calendar.getInstance();
    tmpCal.setTime(d1);
    endWait.set(Calendar.HOUR_OF_DAY,tmpCal.get(Calendar.HOUR_OF_DAY));
    endWait.set(Calendar.MINUTE, tmpCal.get(Calendar.MINUTE));

This way the day, month, year part of the endWait will not be altered.

Upvotes: 1

Seb
Seb

Reputation: 1861

For me it is not giving tomorrow, but waitTo = Thu Jan 01 14:45:00 CET 1970.

The reason for this can be found in the javadoc of SimpleDateFormat:

This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information. For example, the year value of the parsed Date is 1970 with GregorianCalendar if no year value is given from the parsing operation.

Upvotes: 1

Related Questions