Home > Enterprise >  SimpleDateFormat created a Date object with contents different from the given timestamp string [dupl
SimpleDateFormat created a Date object with contents different from the given timestamp string [dupl

Time:09-22

While working with a task involving string array of timestamps, I took reference from this tutorial to convert a String into a Date object. The conversion is going wrong in the month part of the date. I am using Java 11.

FYR Code :

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

public class TimeStampConv {

    public static void main(String[] args) {
        String timeStamp = "02-01-2014 10:02:01:001"; // Date is 2nd January of the year 2014
        try {
            Date d = new SimpleDateFormat("dd-MM-yyyy HH:MM:SS:sss").parse(timeStamp);
            System.out.println(d.toString()); // prints Sun Feb 02 10:00:01 IST 2014
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }

}

CodePudding user response:

Your pattern is wrong, use small m for minutes:

new SimpleDateFormat("dd-MM-yyyy HH:mm:ss:SSS")

Link to docs: SimpleDateFormat

CodePudding user response:

java.time

I recommend that you use java.time, the modern Java date and time API, for your date and time work.

Use this formatter:

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss:SSS", Locale.ROOT);

Parse like this:

    String timeStamp = "02-01-2014 10:02:01:001"; // Date is 2nd January of the year 2014
    LocalDateTime ldt = LocalDateTime.parse(timeStamp, FORMATTER);
    System.out.println(ldt);

Output is:

2014-01-02T10:02:01.001

What went wrong in your code?

Format pattern letters are case sensitive. No matter if using the outdated and troublesome SimpleDateFormat or the modern DateTimeFormatter you need:

  • lower case mm for minute; upper case MM is understood as month, which caused your minute of 02 to be understood as February;
  • lower case ss for second;
  • upper case SSS for fraction of second/millisecond; with SimpleDateFormat upper case S meant milliseocnd, with DateTimeFormatter it means fraction of second.

Since your second and millisecond were both 1, accidentally swapping them didn’t change the result in your particular cases. In most other cases it would make a difference of up to 999 seconds or some quarter of an hour.

Links

CodePudding user response:

Replace your SimpleDateFormat pattern with this:

"dd-MM-yyyy HH:mm:ss:SSS"

It seems like it gets a bit confused because you used MM for both month and minutes. Docs here.

  • Related