Calculate the number of days/hours/minutes/seconds between two dates

There is a variable containing System.currentTimeMillis () at the time of application startup You need to calculate how many days, hours, minutes, and seconds have passed so far

long time_up = System.currentTimeMillis();
.....
long difference = time_up - System.currentTimeMillis();
....
?
Author: HoldFast, 2016-02-17

2 answers

If I understood correctly what was meant, then something like this.

SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

long timeUp = format.parse("2016/01/01 00:00:00").getTime();
long diff = System.currentTimeMillis() - timeUp;

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

StringBuilder sb = new StringBuilder();
sb.append(diffDays + " дней, ");
sb.append(diffHours + " часов, ");
sb.append(diffMinutes + " минут, ");
sb.append(diffSeconds + " секунд");

System.out.println(sb.toString());
 3
Author: enzo, 2016-02-17 11:28:24

You can use the java.util.concurrent.TimeUnit class. Use the toSeconds, toMinutes, toHours, and toDays methods.

d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
long diff = d2.getTime() - d1.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes = TimeUnit.MILLISECONDS.toMinutes(diff);

System.out.println("Time in seconds: " + diffSeconds + " seconds.");         
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
 8
Author: Max, 2016-02-17 11:06:51