-8

I'm using the conversion logic as below to convert an incoming string into date. But, the 'time' part is not getting converted properly in the output. Please find below the code and output.

        String inputDate ="2016-04-22-00.56.03.389289";
        System.out.println(inputDate);
        String frmFormat = "yyyy-MM-dd-HH.mm.ss.SSSSSS";
        String toFormat = "yyyy-MM-dd HH:mm:ss:SSSSSS";
        DateFormat from = new SimpleDateFormat(frmFormat);
        DateFormat to = new SimpleDateFormat(toFormat);
        try {
               Date date = from.parse(inputDate);

               System.out.println("New date:" + to.format(date));

        } catch (Exception e) {
            e.printStackTrace();
        }

OUTPUT: New date:2016-04-22 01:02:32:000289

Please help me to get the right output.

halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

0

Java dates only support a resolution of milliseconds. However, your date requires microsecond resolution.

The problem in your date format is the last part: .SSSSSS. This is the format for milliseconds. And 389289 milliseconds are 389 seconds plus 289 milliseconds. So 389 seconds are added to your date and the milliseconds part is invalid.

Either cut off the last three digits or look for a different Java class that supports microseconds.

Codo
  • 75,595
  • 17
  • 168
  • 206
0

For JDK 8 you can just use:

private static final DateTimeFormatter FRMFORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH.mm.ss.SSSSSS");
private static final DateTimeFormatter TOFORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss:SSSSSS");

The explanation to this is that if you go to the SimpleDateFormat api and the DateTimeFormatter api:

  1. https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
  2. https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html

You will notice that for SimpleDateFormat you have that:

S Millisecond Number 978

And for DateTimeFormatter you have:

S fraction-of-second fraction 978

As you can see, in SimpleDateFormat, you have that S is indeed only a milisecond, whereas in DateTimeFormatter, S, is actually a broader number which means the fraction of a second.