javatimetimestampsimpledateformat

How to convert HH:mm:ss.SSS to milliseconds?


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.

I have tried as follows:

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

Solution

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

    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());        
        }
    }