0
    String timestamp = "2020-05-22 12:58:04.517123+05:30"; 
    Date d = null;
    try {
        d = ext.parse(timestamp);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } */
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse(timestamp);
    System.out.println(date);
    // o/p : Fri May 22 13:06:41 IST 2020

we can see that SimpleDateFormat is producing Future Date. What might be the reason ?

3 Answers3

2

java.time.OffsetDateTime

You have an input and a formatting pattern that both use microseconds. The Date type is limited to milliseconds.

You should not be using the terrible Date and SimpleDateFormat classes. Use only java.time classes.

Edit your input text to comply with the ISO 8601 standard. Replace the SPACE in the middle with T.

String input = "2020-05-22 12:58:04.517123+05:30".replace( " " , "T" ) ;
OffsetDateTime odt = OffsetDateTime.parse( input ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

If you can use java.time for this, do it. Do it like in the answer given by @BasilBorque or provide a pattern that parses Strings of the given format directly without replacing the whitespace with a T to make it the ISO pattern:

public static void main(String[] args) {
    String timestamp = "2020-05-22 12:58:04.517123+05:30";
    // parse the string to an OffsetDateTime using a matching pattern
    OffsetDateTime odt = OffsetDateTime.parse(timestamp,
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSXXXXX"));
    // print the result in the default (ISO) pattern
    System.out.println(odt);
}

The result looks like

2020-05-22T12:58:04.517123+05:30

and is formattable in many different ways.

deHaar
  • 17,687
  • 10
  • 38
  • 51
1

In 12:58:04.517123+05:30 517123 is considered millisecond, which translates to roughly 8 minutes 37 seconds. That's the reason your time is changing. Another important aspect of Date is that it has no concept of timezone, it's merely tells no. of milliseconds from epoch. So when you do toString() it display time in JVM timezone.

Pankaj
  • 2,220
  • 1
  • 19
  • 31