对两个值执行计算并获得正确的时间

时间:2014-06-02 07:13:17

标签: android

我是android的新手我想添加两个实际包含时间的字符串值。 我就像下面那样做了

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

2 个答案:

答案 0 :(得分:1)

我建议你这样做。 使用获取日历实例 Calendar c = Calendar.getInstance();
使用您想要添加12分钟的时间来设置该日历的时间 Date d=new Date();//replace this date object with your parsed date c.setTimeInMillis(d.getTime());
现在以这种方式递增分钟c.roll(Calendar.MINUTE, 12);
 现在用
c.getTime()
获取递增的日期对象。

答案 1 :(得分:0)

对于日期,建议始终使用millis,在您的情况下:

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