user3698393
user3698393

Reputation: 1

perform computation on two values and get correct time

I am new in android i want to add two string values that actually contain time. I did it like below

sunrsetat = "18:58:54"
SimpleDateFormat sdf = new SimpleDateFormat("kk:mm:ss"); 
Date Date1 = sdf.parse(sunrsetat);<--- sunset time value that come from web service
Date Date2 = sdf.parse("00:12:00");<---- i want to add these 12 minutes 

long millse = Date1.getTime() + Date2.getTime();<---problem create here only for hour
long mills = Math.abs(millse);
int Hours = (int) (mills/(60*60*1000));<----- when i subtract 12 minutes it give    
//18:46:43 mean it correct exactly what i want but the problem is that when i add above   
//two values i reference it that Add operation give problem it give result 09:10:43 
//instead of 19:10:43 so i don't know where is the problem..
int Mins = (int) (mills/(1000*60)) % 60;
long Secs = (int) (mills / 1000) % 60;

String time = String.format("%02d:%02d:%02d", Hours, Mins, Secs);
hanfiaiftaritime.setText(time);

Upvotes: 0

Views: 142

Answers (2)

maleto
maleto

Reputation: 11

With dates always is recommended to use millis, in your case:

sunrsetat = "18:58:54"

DateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.US);

Date datebase = sdf.parse(sunrsetat);

long timetoadd = 12*60*1000; //Time in millis

long finaltimeinmillis = datebase.get() + timetoadd;

Calendar c = Calendar.getInstance();
c.setTimeInMillis(finaltimeinmillis);

String time = sdf.format(c.getTime());
hanfiaiftaritime.setText(time);

Upvotes: 0

upenpat
upenpat

Reputation: 685

I suggest you do it this way. Obtain a calendar instance using Calendar c = Calendar.getInstance();
set the time for that calendar using the time into which you want to add 12 minutes into.
Date d=new Date();//replace this date object with your parsed date c.setTimeInMillis(d.getTime());
now increment the minutes this way c.roll(Calendar.MINUTE, 12);
now use
c.getTime()
to get the incremented date object.

Upvotes: 1

Related Questions