简体   繁体   中英

Convert string to time and calculate difference

I have two strings: 1.20.2 and 1.23.0

They are minutes, ie 1.20.2 stands for 1 minute 20.2 seconds.

How can I convert these strings into time values and then do a subtraction?

For example:

1.23.0 - 1.20.2 = 0.2.8

I would prefer to use Joda Time , its a very good API for date/time operations. Otherwise you have to reinvent the wheel...

In my opinion the name of the classes and functions of the API are very intuitional

This is the code ( successfully tested! ):

PeriodFormatter pf = new PeriodFormatterBuilder()
.printZeroAlways() // print zero minutes
.appendMinutes()
.appendSeparator(".")
.appendSecondsWithMillis()
.toFormatter();

Period p1 = pf.parsePeriod("1.20.2");
Period p2 = pf.parsePeriod("1.23.0");

Period diff = p2.minus(p1);
System.out.println(diff.toString(pf));

// output:
// 0.2.800

You should use the SimpleDateFormat , like this:

    String min1 = "1.20.2";
    String min2 = "1.23.0";

    SimpleDateFormat sdf = new SimpleDateFormat("m.ss.S");

    Date parse = sdf.parse(min1);
    Date parse2 = sdf.parse(min2);

    long diff = parse2.getTime() - parse.getTime();
    Date date = new Date(diff);
    String format = sdf.format(date);
    System.out.println(format);

This will print 0.02.998 . To get your expected result of 0.2.8 you have to pass 1.20.200 as min2 as this is how the SimpleDateFormat interprets this value.

Use SimpleDateFormat to convert them to Date objects. Then use Date.getTime() to get the "milliseconds since epoch", compute the difference.

Is the time always in the same format? If so, you can use the split(String regex) method, for example:

String time1 = "1.20.2";
String[] splitTime1 = time1.split(",");

This will give you a string array. I don't know how important it is that you convert them into a DateTime - personally I would convert each item in the array to an int of the same units, for example:

int secondsTime1;
secondsTime1 = (splitTime1[0] * 60) + (splitTime1[1]) + (splitTime1[2] * Math.pow(10, -3));

//Assume you do the same with the second time to get secondsTime2;

int difference = secondsTime1 - secondsTime2;

This should be easy, have you attempted to solve this yourself?

Anyway, pseudo code will look like

For each string
    pos = string.indexOf(".")
    Split string into two parts min, sec based on the index "pos"
    stringSecs = min*60 + sec

Find difference of stringSecs by regular subtraction.

Convert back to required format using min = answer/60, sec=answer%60

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM