Q:

Display hours between 2 dates in java

i have this code, i need show only hours:min:sec, any help?
String var = "1429174464829"; (this is time in System.currentTimeMillis() )
String p = "HH:mm:ss";
SimpleDateFormat f = new SimpleDateFormat(p);
long t = var - System.currentTimeMillis();
String result = f.format(new Date(t));

in example String var, is 1 hours higher than System.currentTimeMillis()
result problem
EDIT: i obtain: result = 21:59:00
thanks

A:

Java 8
Okay, this is a little unpleasant, but will get the job done, this is using Java 8's Time API
LocalDateTime dt1 = LocalDateTime.ofInstant(Instant.ofEpochMilli(1429174464829L), ZoneId.systemDefault());
LocalDateTime dt2 = LocalDateTime.now().plusDays(1);

System.out.println(dt1);
System.out.println(dt2);
    
StringJoiner sj = new StringJoiner(":");
long hours = ChronoUnit.HOURS.between(dt1, dt2);
sj.add(Long.toString(hours));
dt2 = dt2.minusHours(hours);
long mins = ChronoUnit.MINUTES.between(dt1, dt2);
sj.add(Long.toString(mins));
dt2 = dt2.minusMinutes(mins);
long secs = ChronoUnit.SECONDS.between(dt1, dt2);
sj.add(Long.toString(secs));
    
System.out.println(sj);

And will output something like...
2015-04-16T18:54:24.829
2015-04-17T14:10:54.281
19:16:29

Now, if I was to do something like...
LocalDateTime dt2 = LocalDateTime.now().plusDays(4);

I'd get 91:21:10 instead.
I'm hoping someone has a better solution, cause that's kind of a mess...
Joda-Time
If you can't use Java 8, then use Joda-Time
DateTime dt1 = new DateTime(1429174464829L);
DateTime dt2 = DateTime.now().plusDays(4);

System.out.println(dt1);
System.out.println(dt2);
Duration yourDuration = new Duration(dt1, dt2);
Period period = yourDuration.toPeriod();
PeriodFormatter hms = new PeriodFormatterBuilder()
                .printZeroAlways()
                .appendHours()
                .appendSeparator(":")
                .appendMinutes()
                .appendSeparator(":")
                .appendSeconds()
                .toFormatter();
String result = hms.print(period);
System.out.println(result);

Which outputs 91:26:33

A:

There is some time zone issue. we have to specify time zone with SimpleDateFormat. It gives result after adding time difference of your system time zone with standard UTC time zone. By default it takes your local system time zone.
String var = "1429174464829"; (this is time in System.currentTimeMillis() )
String p = "HH:mm:ss";
SimpleDateFormat f = new SimpleDateFormat(p);
f.setTimeZone(TimeZone.getTimeZone("UTC"));

long t = long.parseLong(var) - System.currentTimeMillis();
String result = f.format(new Date(t));

