如何将 HH:mm:ss.SSS 转换为毫秒? [英] How to convert HH:mm:ss.SSS to milliseconds?

查看:40
本文介绍了如何将 HH:mm:ss.SSS 转换为毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串 00:01:30.500 相当于 90500 毫秒.我尝试使用 SimpleDateFormat 给出毫秒,包括当前日期.我只需要以毫秒为单位的字符串表示.我是否必须编写自定义方法,它将拆分和计算毫秒?或者有没有其他方法可以做到这一点?谢谢.

I have a String 00:01:30.500 which is equivalent to 90500 milliseconds. I tried using SimpleDateFormat which give milliseconds including current date. I just need that String representation to milliseconds. Do I have to write custom method, which will split and calculate milliseconds? or Is there any other way to do this? Thanks.

我试过如下:

        String startAfter = "00:01:30.555";
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss.SSS");
        Date date = dateFormat.parse(startAfter);
        System.out.println(date.getTime());

推荐答案

您可以使用 SimpleDateFormat 来完成.你只需要知道两件事.

You can use SimpleDateFormat to do it. You just have to know 2 things.

  1. 所有日期均以 UTC 内部表示
  2. .getTime() 返回自 1970-01-01 00:00:00 UTC 以来的毫秒数.
  1. All dates are internally represented in UTC
  2. .getTime() returns the number of milliseconds since 1970-01-01 00:00:00 UTC.

package se.wederbrand.milliseconds;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Main {        
    public static void main(String[] args) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

        String inputString = "00:01:30.500";

        Date date = sdf.parse("1970-01-01 " + inputString);
        System.out.println("in milliseconds: " + date.getTime());        
    }
}

这篇关于如何将 HH:mm:ss.SSS 转换为毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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