-1

When I use this code to parse a date String, the time is parsed incorrectly. This code prints Wed Feb 14 15:06:06 EST 2018. What date format should I use to parse this input?

String input = "2018-02-14 14:57:59.487927";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");

System.out.println(formatter.parse(input));
ab11
  • 19,770
  • 42
  • 120
  • 207
  • 3
    Your date displays millions of milliseconds, so the time is added to what's parsed. If you truncate the last 3 digits you'll get a date more similar to your desired outcome. – Mena Jun 18 '18 at 14:58
  • I dont work with java but a quick google showed [this](https://stackoverflow.com/a/1459683/2647442) SO answer that shows the format being `yyyy-MM-dd HH:mm:ss.SSS`. Which sounds similar to what Mena mentioned. – Marie Jun 18 '18 at 14:59
  • 1
    @Marie not really, that question is still working with milliseconds, here we're dealing with microseconds – Federico klez Culloca Jun 18 '18 at 15:01
  • 1
    @Mena can I specify the format so it parses the millions of milliseconds? I would htink this would work, but it gives the same result `"yyyy-MM-dd HH:mm:ss.SSSSSS"` – ab11 Jun 18 '18 at 15:01
  • @Mena Gotcha, nvm! – Marie Jun 18 '18 at 15:02
  • I think the date format should be like this : "yyyy-MM-dd HH:mm:ss.SSSSSS" – Amine Messaoudi Jun 18 '18 at 15:02
  • @FedericoklezCulloca I'm using java 1.7, the answer mentions I can use `Timestamp` to resolve nanos, but I'm not clear how... should I extract the date using this `yyyy-MM-dd HH:mm:ss` and then parse the nanos to the timestamp? – ab11 Jun 18 '18 at 15:11
  • @ab11 If you actually need microsecond precision, I'd suggest you get the [ThreeTen Backport](http://www.threeten.org/threetenbp/) of the Java 8 Time classes. --- Anyway, with `SimpleDateFormat`, the uppercase `S` represents *millisecond*, so anything other that exactly 3 of them, i.e. `SSS`, makes no sense at all, and you need to discard any extra fraction digits using `substring`, before parsing the input. – Andreas Jun 18 '18 at 15:24

1 Answers1

1

So far with my testing the best apporach for this is using DateTimeFormatter that will math what you want.

String input = "2018-02-14 14:57:59.487927";
DateTimeFormatter r =DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
LocalDateTime a =LocalDateTime.parse(input,r);
System.out.println(a);

With this you will get

Hour: 14
Minite: 57
Second: 59
Nano: 487927000

And with SimpleDateFormat you will get milisecond always with 927 and so far you will always loose precision.

m   Minute in hour      Number  30
s   Second in minute    Number  55
S   Millisecond         Number  978

So far you best precission is only 3 digits and there is no nanoseconds in SimpleDateFormat.

I suggest to use the new Java 8 Date libraries.

Gatusko
  • 2,503
  • 1
  • 17
  • 25