1

Possible Duplicate:
How can I calculate a time span in Java and format the output?

How to subtract two time by converting them to get long and convert it back to time again?

I tried subtracting two time by converting them to long.

    Long timeSpan = Long.valueOf(timespan.getValue().toString()) * 60;
    Long checkVar = (date.getTime() - testStartTime.getTime()) / 1000;

Now how do i convert the resultant long into time?

That is if the result long is say 30 min i want it to be shown 00:30:00 .

How can i do this?

Thanks in advance

Community
  • 1
  • 1
Sam
  • 1,298
  • 6
  • 30
  • 65

3 Answers3

4

It's trivial to convert your time in seconds into the individual HH:MM:SS components:

int h = checkVar / 3600;
int m = (checkVar / 60) % 60;
int s = (checkVar % 60);

String time = String.format("%02d:%02d:%02d", h, m, s);
Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

As has already been suggested, take a look at Joda Time

PeriodFormatter timeFormatter = new PeriodFormatterBuilder().printZeroAlways().
                appendHours().appendSeparator(":").
                appendMinutes().appendSeparator(":").
                appendSeconds().toFormatter();

DateTime startTime = new DateTime(1972, 3, 8, 15, 30);
DateTime endTime = new DateTime();

Period period = new Period(startTime, endTime);
int days = period.getDays();
int months = period.getMonths();
int years = period.getYears();

System.out.println(period.toString(timeFormatter));
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0
Date elapsed = new Date(checkVar);
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String formatedTime = sdf.format(elapsed);
  • are you _sure_ this can't get confused by timezones? Actually this doesn't even appear to be a legal call to `SimpleDateFormat.format` according to the J2SE 7.0 documentation. – Alnitak Aug 21 '12 at 06:53
  • Why do you say it doesn't appear to a legal call? – Alexandru Burghelea Aug 21 '12 at 07:08
  • 1
    +1 You can set the timezone to be GMT. – Peter Lawrey Aug 21 '12 at 07:19
  • @AlexB because the prototype for that function is `StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos)`. – Alnitak Aug 21 '12 at 07:22
  • @Alnitak It's a method inherited from [DateFormatter](http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#format(java.util.Date)) – Alexandru Burghelea Aug 21 '12 at 07:24
  • @AlexB my mistake - I didn't spot that in the list of inherited methods. – Alnitak Aug 21 '12 at 07:25
  • 1
    This is really not a good idea. Class `java.util.Date` is only suited for storing instants in time, not for storing an amount of time such as "30 minutes". Misusing class `Date` like this can lead to unexpected results. – Jesper Aug 21 '12 at 08:39
  • @Jesper yeah, that's kind of what I was alluding too when I mentioned the potential issue with timezones. – Alnitak Aug 21 '12 at 09:02