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

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

问题描述

我有一个String 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天全站免登陆