解析像“1h 30min"这样的时间字符串 [英] Parsing time strings like "1h 30min"
问题描述
任何人都知道一个 Java 库,它可以将诸如30min"或2h 15min"或2d 15h 30min"之类的时间字符串解析为毫秒(或某种 Duration 对象).Joda-Time 可以做这样的事情吗?
Anyone know of a Java library that can parse time strings such as "30min" or "2h 15min" or "2d 15h 30min" as milliseconds (or some kind of Duration object). Can Joda-Time do something like this?
(我有一个丑陋的长方法来维护这种解析,并希望摆脱它/用更好的东西替换它.)
(I have an ugly long method to maintain that does such parsing and would like to get rid of it / replace it with something that does a better job.)
推荐答案
您可能需要根据自己的格式稍微调整一下,但可以尝试以下方式:
You'll probably have to tweak this a bit for your own format, but try something along these lines:
PeriodFormatter formatter = new PeriodFormatterBuilder()
.appendDays().appendSuffix("d ")
.appendHours().appendSuffix("h ")
.appendMinutes().appendSuffix("min")
.toFormatter();
Period p = formatter.parsePeriod("2d 5h 30min");
请注意,如果您需要使其更灵活,则有一个 appendSuffix
带有 variants
参数.
note that there is a appendSuffix
that takes a variants
parameter if you need to make it more flexible.
更新:Joda Time 已经添加了 Period.toStandardDuration()
,然后您可以使用 getStandardSeconds()
以秒为单位获取 long代码>.
Update: Joda Time has since added Period.toStandardDuration()
, and from there you can use getStandardSeconds()
to get the elapsed time in seconds as a long
.
如果您使用的是没有这些方法的旧版本,您仍然可以通过假设标准的一天 24 小时/小时、60 分钟/小时等来自己计算时间戳(在这种情况下,利用DateTimeConstants
类以避免需要幻数.)
If you're using an older version without these methods you can still calculate a timestamp yourself by assuming the standard 24/hr in a day, 60min/hr, etc. (In this case, take advantage of the constants in the DateTimeConstants
class to avoid the need for magic numbers.)
这篇关于解析像“1h 30min"这样的时间字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!