2

我需要将以下字符串转换为我尝试使用以下代码执行此操作的秒数:

String sDuration = "00:00:24.20";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SS");
videoLength = dateFormat.parse(sDuration);
Logger.debug("Duration: " + videoLength + " timestamp: " + videoLength.getTime());

但我得到的回应是:

Duration: Thu Jan 01 00:00:24 GMT 1970 timestamp: -3575980

第一个看起来不错,但我需要 .getTime() 进行计算,我得到一个负数?我预计会得到类似 24200 的东西。

4

4 回答 4

4

不完全确定是否Date打算用于持续时间(而不是时间点)。

不过,这是另一种方法:

String[] hms = sDuration.split(":");

double sec = Integer.parseInt(hms[0]) * 3600
           + Integer.parseInt(hms[1]) * 60
           + Double.parseDouble(hms[2]);
于 2012-05-24T11:05:48.953 回答
2

还有一种方法:

String sDuration = "00:00:24.20";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SS");
Date end = dateFormat.parse(sDuration);
Date start = dateFormat.parse("00:00:00.00");
System.out.println("Duration: " + (end.getTime() - start.getTime()));
于 2012-05-24T11:08:28.577 回答
1

我一直在做一些测试,这些背后的原因是你所在的时区。

如果我做

Date begin = new Date().setTime(0);
System.out.println(begin);

我得到这个输出:

1970 年 1 月 1 日星期四 01:00:00 CET

因此,对于我的时区,00:00::00 和 01:00:00 之间的任何时间都将具有负毫秒数。

于 2012-05-24T11:18:38.463 回答
0

不要忘记 SimpleDateFormat不是线程安全的,它应该这样调用:

    private static final ThreadLocal<SimpleDateFormat> SIMPLE_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
    @Override protected SimpleDateFormat initialValue() { return new SimpleDateFormat("format"); };
    @Override public void set(SimpleDateFormat value) { /*...*/ };
};
于 2012-05-24T11:28:10.213 回答