1

How can I convert the difference of the current time a given time to create a string with the time format: HH:mm ? ex. 18:36

I did the following but, it is not 24Hour format, it will add AM/PM to the end, and it is 3 hours off.

        java.util.Date today = new java.util.Date();
        java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
        java.util.Date parsedDate = dateFormat.parse(time);
        java.sql.Timestamp ts2 = new java.sql.Timestamp(parsedDate.getTime());

        long nowTime = ts1.getTime();
        long givenTime = ts2.getTime();

        long timeDiff = givenTime - nowTime;

        //convert to string
        java.util.Date d = new java.util.Date(timeDiff);
        result = DateFormat.getTimeInstance(DateFormat.SHORT).format(d);
        //Outputs: 6:56 PM for example
Ryan R
  • 8,342
  • 15
  • 84
  • 111
  • 1
    possible duplicate of [How can I calculate a time span in Java and format the output?](http://stackoverflow.com/questions/635935/how-can-i-calculate-a-time-span-in-java-and-format-the-output) – Thilo Jun 15 '11 at 01:53
  • Also, a possible duplicate : http://stackoverflow.com/questions/2949699/converting-time-from-hhmmss-to-hhmm-in-java – Saurabh Gokhale Jun 15 '11 at 01:55

2 Answers2

3

Once easy thing you can do is call getTime() for both dates and then subtract them like so:

long timeDiff = today.getTime() - ts1.getTime()

That should give you the difference in miliseconds between the two times. After that you know that one second is 1k miliseconds, 1min i 60s, 1h is 60 minutes and so on.

davorb
  • 613
  • 1
  • 9
  • 17
2

Take a look at Commons Lang DurationFormatUtils.

Or Joda-Time's PeriodFormatter.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • there's really no reason to use a third-party library. – mre Jun 15 '11 at 02:00
  • 1
    @mre: Actually, given Java's awful Date and Calendar implementation, there is every reason to use third party libraries. For this one particular instance, vodnik's answer will suffice, but that is rarely the case when working with dates and/or times. +1 from me to make up for your downvote. – Amos M. Carpenter Jun 07 '12 at 01:29