SimpleDateFormat appears to fail with "yyyy-MM-dd HH:mm:ss.SSS0"

24,678

I do not know why would you need to add the zero (0) at the end of your pattern, but you should wrap the not pattern letters inside '' to make them work:

final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS'0'");

More info:


The problem with your code is in this line

System.out.println(format.parse(d));

Trying to parse more than 3-digit milliseconds to java.util.Date will result in an exception. The pattern to parse the String should be

"yyyy-MM-dd HH:mm:ss.SSS" //without the zero at the end, now your whole code will work...

If you're working with nanoseconds or your data have them, you could ignore these values, also nanoseconds are not supported in Java Date/Time API (in the documentation they don't even mention it).

If you really, really need to have the nanoseconds for diverse purposes, then you should stick to use a String instead of a Date object.

Share:
24,678
cellige
Author by

cellige

Updated on July 27, 2020

Comments

  • cellige
    cellige almost 4 years

    Why doesn't the following work? It appears that the literal zero at the end is the cause...

    final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS0");
    format.setLenient(false);
    
    String d = format.format(new Date());
    System.out.println(format.parse(d));
    
  • cellige
    cellige almost 12 years
    Not to mention the documentation says that the quoting is for the letter formatters. Doesn't say you need it, and from my little testing doesn't appear to make a difference for digits.
  • Luiggi Mendoza
    Luiggi Mendoza almost 12 years
    How do your date value looks like? Why would you want to parse a date with an additional zero?
  • Luiggi Mendoza
    Luiggi Mendoza almost 12 years
    @RichardSitze if you're a scientist and need to use the nanoseconds for whatever operation you could need, you should handle these values by yourself, the Java API can't help you on this. Still, there is the System.nanoTime() method that handles the current time with nanoseconds in a long variable. You could come up with a nice way to convert up to the millisecond part in long, then multiplicate it by 1000 and add the nanoseconds (lot of hard work...)
  • Richard Sitze
    Richard Sitze almost 12 years
    @Luiggi your answer is correct in so far as describing the behavior of parse wrt milliseconds. However I believe the correct "answer" is simply that SimpleDateFormat.parse doesn't implement the described spec. I see this as a (minor) defect. You've described the limitations, and have suggested reasonable work-arounds - and that's great. To add to the misery, your suggestion of quoting should also work... and it doesn't.
  • Luiggi Mendoza
    Luiggi Mendoza almost 12 years
    @RichardSitze I've edited the answer. The problem is not in the format, is in the parse, as I've explained in a different section.