将持续时间字符串解析为毫秒

我需要解析一个持续时间字符串,格式为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 

然后使用TimeUnit将它们放在一起并转换为毫秒。

我想我的问题是,这看起来有点矫枉过正,可以做得更容易吗? 关于日期和时间戳的大量问题出现了,但这可能有点不同。

使用Pattern是一种合理的方法。 但为什么不用一个人来获得所有四个领域呢?

 Pattern p = Pattern.compile("(\\d+)d\\s+(\\d+)h\\s+(\\d+)m\\s+(\\d+)s"); 

然后使用索引组提取。

编辑:

基于你的想法,我最终编写了以下方法

 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; } 

从JodaTime库中查看PeriodFormatterPeriodParser

您也可以使用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(); 

现在,所有这些(特别是toDurationFrom(...)部分)可能看起来很棘手,但我真的建议你研究JodaTime如果你正在处理Java中的句点和持续时间。

另请参阅有关从JodaTime期间获取毫秒数的答案,以获得进一步说明。

Java 8中新的java.time.Duration类允许您解析开箱即用的持续时间:

 Duration.parse("P98DT01H23M45S").toMillis(); 

格式略有不同,因此需要在解析之前进行调整。