3

I have String initialTime= "10:30:00" I am converting it into time like so:-

DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Time time = new Time(date.getTime());
int initHour = time.getHours()
int initMind = time.getMinutes();

Further I have two values;

int hour, mins;

The hour value can be anything from 0-10; mins value can be 0,15,30,45.

The user selects a time by selecting hour and mins. As soon as the user selects the values they should get added to the initialTimeand shown in finalTIme

So if:-

hour=0 and mins=15 then finalTIme=10:45:00
hour=0 and mins=35 then finalTIme=11:00:00
hour=0 and mins=45 then finalTIme=11:15:00

I tried doing something like:-

if(hour==0 && mins==0)
{
    finalTime = initialTime;
}

else if(hour==0 && mins>0 && mins <30)
{
   mins = initMins + mins 
}
else if(hour==0 && mins>0 && mins >=30)
{
   hours = hours+1;
   mins = mins-60;
}

But I did not get the required output. HOw can I do it in a less complicated manner?

Stack Over
  • 85
  • 1
  • 2
  • 8
  • possible duplicate of [Java : how to add 10 mins in my Time](http://stackoverflow.com/questions/9015536/java-how-to-add-10-mins-in-my-time) and [this](http://stackoverflow.com/q/5894726/642706) and many others. – Basil Bourque Sep 13 '14 at 06:10

1 Answers1

5

You can use java.util.Calendar class:

DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(initialTime);
Calendar cal = Calendar.getInstance();
cal.setTime(date);

cal.add(Calendar.HOUR_OF_DAY, hours);
cal.add(Calendar.MINUTE, minutes);

date = cal.getTime();

You might also consider the new Date API from JDK 8.

Arek
  • 3,106
  • 3
  • 23
  • 32