Search code examples
javadatetimesimpledateformatjava.util.date

Convert String to Date with Milliseconds


I know that there many subject of how to convert from String to Date, I'm using 'SimpleDateFormat' and i have a string that contains (Year, Month, Day , Hour, Minute, second, Milliseconds) but when I'm using the 'SimpleDateFormat' the Milliseconds is not set here the code and the output:

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

String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date dateFormatter = formatter.parse(strDate);

System.out.println(dateFormatter);

Output:

Thu Aug 27 10:06:07 WAT 2020

I want the result in type Date


Solution

  • The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds.

    You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.

    If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:

    System.out.println(formatter.format(dateFormatter));
    

    outputs 2020-08-27T10:06:07.413