如何编写一个简单的java程序,可以在单个单元中转换一系列时间? (例如以毫秒为单位)[关闭]在线尝试!

问题描述 投票:0回答:2

我在excel文件中有一系列时间戳(列式),下面是一些示例:

30m1.566s 
30m0.706s 
30m34.197s
30m1.545s
30m1.148s
30m1.791s
30m1.903

我想将这些时间转换为单个单位 - 毫秒(例如30毫秒至903秒的时间,以毫秒为单位)。删除每个'm'和's'将非常困难,因为有100个时间戳,所以我只是试图用java或c编写一个程序来使用该文件在毫秒内转换所有时间但是无法做到它。

我非常感谢任何帮助和建议。非常感谢。

Larger data set

java excel datetime timestamp
2个回答
1
投票

那些不是时间戳 - 不是因为它们代表了一个特定的时刻。实际上,它们是持续时间 - 一段时间。

另一种方法是将字符串转换为ISO8601 compliant format并使用java.time.Duration解析它们:

String s = "30m1.791s";
s = "PT" + s.replace("m", "M").replace("s", "S");
Duration duration = Duration.parse(s);
System.out.println(duration.toMillis()); // 1801791

0
投票

Code [Try it online!]

import java.util.regex.*;
class Main {
    public static void main(String... args) {

        Pattern p = Pattern.compile("([0-9]+)m([0-9]+)\\.([0-9]+)s");
        Matcher m = p.matcher(args[0]);

        m.find();

        int minutes = Integer.parseInt(m.group(1));
        int seconds = Integer.parseInt(m.group(2));
        int millis = Integer.parseInt(m.group(3));

        System.out.println((minutes * 60000) + (seconds * 1000) + millis);
    }
}

Explanation

这使用上面的正则表达式找到3个部分,将它们转换为int然后将它们相加

© www.soinside.com 2019 - 2024. All rights reserved.