3

After subtracting time 1:10 and 2:15 using java I am getting the ouput as long which is in milliseconds -3900000. Then I convert this millisecond into time format, then the output produced is Output : -01:-05:00.

The output I am expecting is like -01:05:00. There should be only one negative sign in the output

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

public class TimeAddition {
    public static void main(String args[]) throws ParseException {
        String b = "1:10";
        String a = "2:15";

     // converting String time into dateTime   
        DateFormat sdf = new SimpleDateFormat("hh:mm");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date bTime = sdf.parse(b);
        Date aTime = sdf.parse(a);

        long totalTime = bTime.getTime() - aTime.getTime();

        System.out.println("Total time in millisecond = " + totalTime);

        long millis = totalTime;

        String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis)
                    - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis)
                    - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

        System.out.println("Time format " + hms);   
    }

}

Output produced : Total time in millisecond = -3900000 Time format -1:-5:00

Expected Time format = -01:05:00

Shamith S Kumar
  • 97
  • 1
  • 1
  • 7
  • Please add your code so we can see what's wrong and advise for correction. – AR1 Jan 09 '17 at 09:48
  • make the milliseconds to positive and then change into time format, after then put a negative sign in front of it. – jack jay Jan 09 '17 at 09:48
  • Well, hard to tell the problem from text only. Please show the code you use to convert the milliseconds into time (only that part ;) ). PS : try to edit the question to improve the format. Using some tags to see the values you have – AxelH Jan 09 '17 at 09:49
  • I cannot add the negative sign to the final output because its output will be either positive or negative, it can't be predicted – Shamith S Kumar Jan 09 '17 at 10:05
  • Related (not a dupe): [How to format a duration in java? (e.g format H:MM:SS)](http://stackoverflow.com/questions/266825/how-to-format-a-duration-in-java-e-g-format-hmmss/18633466) – Ole V.V. Jan 09 '17 at 10:52

4 Answers4

2

You should do something like that:

  • you compute if you should add a sign (-) or not.
  • if the amount of time is negative, you get its absolute value (you can also use Maths.abs).
  • you format it with the sign before.

Which gives:

String sign = totalTime < 0 ? "-":"";
long millis = totalTime < 0 ? -totalTime:totalTime;
String hms = String.format("%s%02d:%02d:%02d", sign, TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis)
                       - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis)
                        - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
NoDataFound
  • 11,381
  • 33
  • 59
0

Just Change this code :

TimeUnit.MILLISECONDS.toMinutes(millis)
                - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis))

to this code:

TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)) - TimeUnit.MILLISECONDS.toMinutes(millis)

Tested successsfully

Tahir Hussain Mir
  • 2,506
  • 2
  • 19
  • 26
0

You can use this approach as well to get time difference easily.

public static void main(String[] args)
{
     String time1 = "01:10:00";
     String time2 = "02:15:00";
     String finalDiff;

     try{
          SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
          Date date1 = format.parse(time1);
          Date date2 = format.parse(time2);

          long difference = date1.getTime() - date2.getTime();
          Date d;

          if(difference<0) {
              d = new Date(-1*difference);
              finalDiff = "-"+ format.format(d);
          }
          else{
              d = new Date(difference);
              finalDiff = format.format(d);
          }

          System.out.println(finalDiff);// gives the difference as required by you.

     }catch(Exception e){}
} 
jack jay
  • 2,493
  • 1
  • 14
  • 27
0

Date and SimpleDateFormat are both oldfashioned and unsuited for the purpose. They were intended for a point in time and its representation in a certain timezone, never for the length of a time interval. I would not be comfortable using them for the latter, or I would at the very least test thoroughly on computers running different time zones.

My suggestion is to use the new java.time package. Despite the fact discussed in the comments to this answer that it does not include a duration formatter.

    String b = "1:10";
    String a = "2:15";

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:mm", Locale.ROOT);
    LocalTime end = LocalTime.parse(b, dtf);
    LocalTime start = LocalTime.parse(a, dtf);
    Duration totalTime = Duration.between(start, end);
    String sign;
    if (totalTime.isNegative()) {
        totalTime = totalTime.negated();
        sign = "-";
    } else {
        sign = "";
    }
    long hours = totalTime.toHours();
    totalTime = totalTime.minusHours(hours);
    long minutes = totalTime.toMinutes();
    totalTime = totalTime.minusMinutes(minutes);
    long seconds = totalTime.getSeconds();
    System.out.format("%s%d:%02d:%02d%n", sign, hours, minutes, seconds);

This prints:

-1:05:00

The price is we need to handle a negative interval explicitly. The good news is the library classes do all calculations for us: calculating the length of time and conversion to hours, minutes and seconds.

Community
  • 1
  • 1
Ole V.V.
  • 81,772
  • 15
  • 137
  • 161