I need to show in my software the amount of days, hours and minutes that a particular event occurred.
I get a string with the value of the last event and calculating the amount of time that the event occurred.
..
lastEvent: String = lastEventOcorr (); "16.07.2013 19:20:06"
..
example:
Last event occurred: 3 Days 6 Hours 45 Minutes and 42 Seconds
or
Last event occurred: 5 Minutes 30 Seconds
..
There is a practical way to do this calculation?
I really appreciate all the help.
Thank you very much
Here are several approaches on how to parse your String
into a Date
instance.
Afterwards you need to calculate the difference between the parsed Date
and the current date ( new Date()
).
Finally you can format your resulting difference according to your preferences.
I would strongly suggest simply doing System.currentTimeMillis()
at the start of the event and at the end of the event.
long start = System.currentTimeMillis();
//EVENT
long stop = System.currentTimeMillis();
long difference = stop - start;
Then with a little math you can get it in a nicer format.
int seconds=(difference/1000)%60;
int minutes=(difference/(1000*60))%60;
int hours=(difference/(1000*60*60))%24;
Here is an example on how to count days, you can add hours and mins to this.
long MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
String lastEvent = "13.07.2013 10:20:06";
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm:ss");
Date lastEventDate = sdf.parse(lastEvent);
Date currentDate = new Date();
long timeElapsed = currentDate.getTime() - lastEventDate.getTime();
long diffInDays = timeElapsed / MILLIS_IN_DAY;
System.out.println(diffInDays);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.