0

I have two time STRING values :

First : 1:12.203
Second : 1:04.009

Milliseconds come after '.'

How can I receive the subtraction of this two values? I need to have 0:08.194 or something like this.

I don't know which variables to use and how it realize, so I'll be glad for your help and properly piece of code.

2 Answers2

3

You should use Duration to store these things. There is no nice declarative way to parse your custom format, but you can do so quite easily using a regular expression.

private static Duration parseDuration(String duration)
{
    Pattern pattern = Pattern.compile("(\\d+):(\\d{2})\\.(\\d{3})");
    Matcher matcher = pattern.matcher(duration);

    if (matcher.matches())
    {
        long mins = Long.valueOf(matcher.group(1));
        long secs = Long.valueOf(matcher.group(2));
        long millis = Long.valueOf(matcher.group(3));

        return Duration.ofMinutes(mins).plusSeconds(secs).plusMillis(millis);
    }
    throw new IllegalArgumentException("Invalid duration " + duration);
}

Sample usage:

Duration diff = parseDuration("1:12.203").minus(parseDuration("1:04.009"));

If you want to format the difference nicely using the same format, see How to format a duration in java? (e.g format H:MM:SS)

Michael
  • 41,989
  • 11
  • 82
  • 128
1

This answer is based on: https://stackoverflow.com/a/4927884/5622596

Imports needed:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

Code that prints out the time : 00:08.194

    String first =  "1:12.203";
    String second = "1:04.009";

    SimpleDateFormat formater = new SimpleDateFormat("mm:ss.SSS");

    try {
        Date dateStart = formater.parse(first);
        Date dateEnd = formater.parse(second);

        long milliSeconds = dateStart.getTime() - dateEnd.getTime(); 

        Date timeDiff = new Date(milliSeconds);

        System.out.println(formater.format(timeDiff));
    } catch (ParseException e) {
        e.printStackTrace();
    }

If you are looking for a method to return a string.Try something like this:

@Test
public void printDiff() {
    String first = "1:12.203";
    String second = "1:04.009";

    try {
        System.out.println(getTimeDiffString(first, second));
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

private String getTimeDiffString(String first, String second) throws ParseException {
    SimpleDateFormat formater = new SimpleDateFormat("mm:ss.SSS");

    //Get number of milliseconds between times: 
    Date dateStart = formater.parse(first);
    Date dateEnd = formater.parse(second);
    long milliSeconds = dateStart.getTime() - dateEnd.getTime();

    //Convert time difference to mm:ss.SSS string
    Date timeDiff = new Date(milliSeconds);
    return formater.format(timeDiff).toString();

}
jspek
  • 438
  • 3
  • 10