将持续时间字符串解析为毫秒 [英] Parsing duration string into milliseconds

查看:73
本文介绍了将持续时间字符串解析为毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将格式为98d 01h 23m 45s的持续时间字符串解析为毫秒.

I need to parse a duration string, of the form 98d 01h 23m 45s into milliseconds.

我希望像这样的持续时间中有一个SimpleDateFormat的等价物,但是我什么也找不到.有人会建议为此目的使用或支持SDF吗?

I was hoping there was an equivalent of SimpleDateFormat for durations like this, but I couldn't find anything. Would anyone recommend for or against trying to use SDF for this purpose?

我当前的计划是使用正则表达式来匹配数字并执行类似的操作

My current plan is to use regex to match against numbers and do something like

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 将它们放在一起并转换为毫秒.

and then use TimeUnit to put it all together and convert to milliseconds.

我想我的问题是,这似乎有点过头了,它可以简化吗?出现了很多有关日期和时间戳的问题,但这也许有些不同.

I guess my question is, this seems like overkill, can it be done easier? Lots of questions about dates and timestamps turned up but this is a little different, maybe.

推荐答案

使用Pattern是一种合理的方法.但是,为什么不使用单个字段来获取所有四个字段呢?

Using a Pattern is a reasonable way to go. But why not use a single one to get all four fields?

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

然后使用索引组提取.

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

Building off of your idea, I ultimately wrote the following method

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

这篇关于将持续时间字符串解析为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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