“HH:MM:SS”中的秒数

时间:2010-07-08 17:51:07

标签: java string parsing

获取字符串表示形式的秒数的最佳方法是什么,例如“hh:mm:ss”?

显然Integer.parseInt(s.substring(...))* 3600 + Integer.parseInt(s.substring(...))* 60 + Integer.parseInt(s.substring(...))的工作原理

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

谢谢!

4 个答案:

答案 0 :(得分:12)

基于pakores solution

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

简化(不多):

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

答案 1 :(得分:3)

原创方式: Calendar版本(根据评论中的建议更新):

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = dateFormat.parse(string);
//Here you can do manually date.getHours()*3600+date.getMinutes*60+date.getSeconds();
//It's deprecated to use Date class though.
//Here it goes an original way to do it.
Calendar time = new GregorianCalendar();
time.setTime(date);
time.setTimeZone(TimeZone.getTimeZone("UTC"));
time.set(Calendar.YEAR,1970); //Epoc year
time.set(Calendar.MONTH,Calendar.JANUARY); //Epoc month
time.set(Calendar.DAY_OF_MONTH,1); //Epoc day of month
long seconds = time.getTimeInMillis()/1000L;

免责声明:我已经用心做了,只看文档,所以也许有一两个错字。

答案 2 :(得分:1)

joda-time是1个选项。事实上,我更喜欢该库用于所有日期操作。我正在通过java 5 javadoc找到这个enum类,它对你来说简单实用。 java.util.concurrent.TimeUnit中。看看convert(...)方法。 http://download.oracle.com/docs/cd/E17476_01/javase/1.5.0/docs/api/java/util/concurrent/TimeUnit.html

答案 3 :(得分:0)