How to add part of time in Android
I have a code returning me a string (HH:mm).
SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date dateObj;
try {
dateObj = curFormater.parse(start);
SimpleDateFormat postFormater = new SimpleDateFormat("HH:mm");
String newDateStr = postFormater.format(dateObj);
startView.setText(newDateStr);
Emission_start = newDateStr;
} catch (ParseException e) {
// TODO Auto-generated catch block
Log.d(" * Error", e.toString());
}
It works great... But right now I would like to:
- add x (is dynamically provided) minutes (x = from 5 to 1000 minutes) and transform to time (example time:3:45, add 25 minutes, transform to time 4:10)
- Get current time and calculate difference between current time and time from step 1 (4:10)
- Get time 开发者_如何学Cdifference (from step 2) in minutes!
Thanks for your help!
I haven't tested, but something like this should work:
long newDate = dateObj.getTime() + (x * 60 * 1000)
long diff = System.currentTimeMillis() - newDate
double diffInMins = diff / (60.0 * 1000.0)
use Calendar
Calendar calInstance = new GregorianCalendar(); calInstance.setTime(dateObj);
Then add any fragment you want, for minutes do
calInstance.add(Calendar.MINUTE, XX)
To, transform use your formatter
postFormatter.format(calInstance.getTime());
is trivial
Diff in minutes can be calculated easily as well
long diffInMins = (currTimeInMillis - calInstance.getTimeInMillis())/(1000 * 60);
精彩评论