Java SimpleDateFormat does not parse correctly (I am using the correct uppercase/lowercase letters..)

I know this has been asked several times and I am risking a downvote/duplicate close, but most of the questions posted here were resolved by chaing YYYY into yyyy..so, searching does not really help :/

These are the given timestamps inside the block

date new Block: 2017-11-02T06:17:05.079481
date old Block: 2017-11-02T06:17:04.608960

My conversion code:

 public static Date getDate(JSONObject block){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
    try {
       return sdf.parse(block.get("timestamp").toString());
    } catch (ParseException e) {
        e.printStackTrace();
        return new Date(0);
    }
}

And this is the result of parse

date new block: Thu Nov 02 06:18:24 KST 2017 
date old block: Thu Nov 02 06:27:12 KST 2017

How is that possible? The new block was created after the old block, as seen in the timestamp. but now it is the other way around

Jon Skeet
people
quotationmark

How is that possible? The new block was created before the old block, as seen in the timestamp. but now it is the other way around

S in a SimpleDateFormat format string always represents milliseconds - not just "fractions of a second" which is what you're assuming at the moment.

Your "new" block is being parsed as adding 79481 milliseconds whereas the "old" block has 608960.

That explains the results, but doesn't give you a way forward. There are two options here:

  • Use java.time.* - this is a much more modern API, with nanosecond precision instead of millisecond precision.
  • Drop the last three characters of your inputs, and parse to only millisecond precision.

people

See more on this question at Stackoverflow