解析时间字符串,如“1小时30分钟”, [英] Parsing time strings like "1h 30min"

查看:111
本文介绍了解析时间字符串,如“1小时30分钟”,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道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时间已经添加 Period.toStandardDuration() ,从那里你可以使用 getStandardSeconds() 的形式获取经过的时间(以秒为单位)很长

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.)

这篇关于解析时间字符串,如“1小时30分钟”,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆