Cra*_*igy 7 java string time parsing
我需要将表单的持续时间字符串解析98d 01h 23m 45s为毫秒.
我希望有相当于这样的SimpleDateFormat持续时间,但我找不到任何东西.是否有人建议赞成或反对尝试使用SDF用于此目的?
我目前的计划是使用正则表达式来匹配数字并执行类似的操作
Pattern p = Pattern.compile("(\\d+)");
Matcher m = p.matcher("98d 01h 23m 45s");
if (m.find()) {
int days = Integer.parseInt(m.group());
}
// etc. for hours, minutes, seconds
Run Code Online (Sandbox Code Playgroud)
然后使用TimeUnit将它们放在一起并转换为毫秒.
我想我的问题是,这看起来有点矫枉过正,可以做得更容易吗?关于日期和时间戳的很多问题都出现了,但这可能有点不同.
npe*_*npe 11
退房PeriodFormatter并PeriodParser从JodaTime图书馆.
您还可以使用PeriodFormatterBuilder为此字符串构建解析器
String periodString = "98d 01h 23m 45s";
PeriodParser parser = new PeriodFormatterBuilder()
.appendDays().appendSuffix("d ")
.appendHours().appendSuffix("h ")
.appendMinutes().appendSuffix("m ")
.appendSeconds().appendSuffix("s ")
.toParser();
MutablePeriod period = new MutablePeriod();
parser.parseInto(period, periodString, 0, Locale.getDefault());
long millis = period.toDurationFrom(new DateTime(0)).getMillis();
Run Code Online (Sandbox Code Playgroud)
现在,所有这些(特别是toDurationFrom(...)部分)可能看起来很棘手,但我真的建议你研究一下JodaTime你是在处理Java中的句点和持续时间.
另请参阅此答案,了解从JodaTime期间获取毫秒数以获得进一步说明.
使用a Pattern是一种合理的方式.但为什么不用一个单一来获得所有四个领域呢?
Pattern p = Pattern.compile("(\\d+)d\\s+(\\d+)h\\s+(\\d+)m\\s+(\\d+)s");
Run Code Online (Sandbox Code Playgroud)
然后使用索引组提取.
编辑:
基于你的想法,我最终编写了以下方法
private static Pattern p = Pattern
.compile("(\\d+)d\\s+(\\d+)h\\s+(\\d+)m\\s+(\\d+)s");
/**
* Parses a duration string of the form "98d 01h 23m 45s" into milliseconds.
*
* @throws ParseException
*/
public static long parseDuration(String duration) throws ParseException {
Matcher m = p.matcher(duration);
long milliseconds = 0;
if (m.find() && m.groupCount() == 4) {
int days = Integer.parseInt(m.group(1));
milliseconds += TimeUnit.MILLISECONDS.convert(days, TimeUnit.DAYS);
int hours = Integer.parseInt(m.group(2));
milliseconds += TimeUnit.MILLISECONDS
.convert(hours, TimeUnit.HOURS);
int minutes = Integer.parseInt(m.group(3));
milliseconds += TimeUnit.MILLISECONDS.convert(minutes,
TimeUnit.MINUTES);
int seconds = Integer.parseInt(m.group(4));
milliseconds += TimeUnit.MILLISECONDS.convert(seconds,
TimeUnit.SECONDS);
} else {
throw new ParseException("Cannot parse duration " + duration, 0);
}
return milliseconds;
}
Run Code Online (Sandbox Code Playgroud)