-1

Basically I'm trying to convert string data to Timestamp format. When I converted data to timestamp format, SimpleDateFormat added three minutes. Because milisecond data equals 3 minute.But I want to preserve milisecond data on timestamp value.

Code:

public Double TimestampTest(String Timestamp ){
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date parsedDate = null;
    try {
        parsedDate = dateFormat.parse(Timestamp);   
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
...
} 

Timestamp value

2002-04-17 23:45:58.983

For test case

System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2015-04-22T19:54:11.219983Z"));
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'Z'").parse("2015-04-22 19:54:11.219983Z"));

Results are same for both of them

Wed Apr 22 19:57:50 EEST 2015

Wed Apr 22 19:57:50 EEST 2015

Because

219 983 milliseconds = 3.66638333 minutes

To sum up I want to preserve ms data .Is there any way to do it ?

dgn
  • 103
  • 5
  • 15
  • `SimpleDateFormat` has millisecond precision - 3 digits after decimal point. If there's more than 3 you get strange results: https://stackoverflow.com/q/36055717/7605325 - https://stackoverflow.com/q/44979279/7605325 –  Jul 09 '17 at 11:50
  • 1
    Possible duplicate of [SimpleDateFormat cannot parse milliseconds with more than 4 digits](https://stackoverflow.com/questions/36055717/simpledateformat-cannot-parse-milliseconds-with-more-than-4-digits) –  Jul 09 '17 at 11:52

1 Answers1

2

If I understand, what you have at the end of your string are microseconds, not milliseconds. The old, obsolete Date and SimpleDateFormat classes have no support for microseconds. But you can use the new java.time classes:

System.out.println(ZonedDateTime.parse("2015-04-22T19:54:11.219983Z",
                                       DateTimeFormatter.ofPattern(("yyyy-MM-dd'T'HH:mm:ss.SSSSSSVV"))));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    I believe that in this case you can just use `parse` without a formatter - although I'm not in front of a computer to test –  Jul 09 '17 at 12:32
  • @Hugo is correct. If you have a requirement of exactly 6 decimals, you need a formatter, but for most uses the explicit formatter is just cluttering the code. `ZonedDateTime.parse("2015-04-22T19:54:11.219983Z")` works. Otherwise the answer is a very good one. – Ole V.V. Jul 18 '17 at 08:30