在"HH:MM:SS"中的秒数. [英] Number of seconds in "HH:MM:SS"

查看:85
本文介绍了在"HH:MM:SS"中的秒数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以"hh:mm:ss"之类的字符串表示形式获取秒数的最佳方法是什么?

What's the best way to get the number of seconds in a string representation like "hh:mm:ss"?

显然是Integer.parseInt(s.substring(...))* 3600 + Integer.parseInt(s.substring(...))* 60 + Integer.parseInt(s.substring(...))有效

Obviously Integer.parseInt(s.substring(...)) * 3600 + Integer.parseInt(s.substring(...)) * 60 + Integer.parseInt(s.substring(...)) works.

但是我不想对此进行测试,并重新发明,我希望有一种方法可以使用DateTimeFormat或标准库中的其他类.

But I don't want to test that, and reinvent the wheal, I expect there is a way to use DateTimeFormat or other classes from standard libraries.

谢谢!

推荐答案

基于 pakores 解决方案:

    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    Date reference = dateFormat.parse("00:00:00");
    Date date = dateFormat.parse(string);
    long seconds = (date.getTime() - reference.getTime()) / 1000L;

reference用于补偿不同的时区,并且夏令时没有问题,因为SimpleDateFormat不使用实际日期,它返回Epoc日期(1970年1月1日=无DST).

reference is used to compensate for different timezones and there is no problem with daylight saving time because SimpleDateFormat does NOT use the actual date, it return the Epoc date (January 1st, 1970 = no DST).

简化(不多):

    DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = dateFormat.parse("01:00:10");
    long seconds = date.getTime() / 1000L;

但我还是来看看Joda-Time ...

but I would still have a look at Joda-Time...

这篇关于在"HH:MM:SS"中的秒数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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