Search code examples
javasimpledateformattrailing

Java SimpleDateFormat cut trailing 0-digits of SSS


hi i have an simple date format

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

It formats the date like this

2014-04-23 13:15:59.390 

is it possible to remove the trailing 0, except when the digit it it is not 0?

2014-04-23 13:15:59.39

ok i've found my problem

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); 

gives me what i want, the problem is that i'm comparing it with a date-string which comes from a database.

The database reads it from a timesamp column, which contains the correct value, but i'm reading it with a

resultSet.getString(i)

and for some reason it cutts the last digit... So my question should be, why does resultSet.getString cut the last character when reading a date field?


Solution

  • Use String methods to trim a trailing zero:

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date).replaceAll("0$", "");
    

    To trim up to 2 trailing zeroes:

    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(date).replaceAll("0?0$", "");