我有两个时间STRING值:
First : 1:12.203
Second : 1:04.009
毫秒在“。”之后。
如何获得这两个值的减法? 我需要有0:08.194或类似的内容。
我不知道使用哪个变量以及如何实现,所以很高兴为您提供帮助并提供适当的代码。
答案 0 :(得分:3)
您应该使用Duration
来存储这些内容。没有很好的声明性方法来解析您的自定义格式,但是您可以使用正则表达式轻松地做到这一点。
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);
}
样品用量:
Duration diff = parseDuration("1:12.203").minus(parseDuration("1:04.009"));
如果要使用相同的格式很好地格式化差异,请参见How to format a duration in java? (e.g format H:MM:SS)
答案 1 :(得分:1)
此答案基于:https://stackoverflow.com/a/4927884/5622596
所需的进口:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
显示时间的代码: 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();
}
如果您正在寻找一种返回字符串的方法。请尝试如下操作:
@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();
}