3

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?

Meno Hochschild
  • 42,708
  • 7
  • 104
  • 126
wutzebaer
  • 14,365
  • 19
  • 99
  • 170

3 Answers3

2

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$", "");
Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

On the resulting string, do a replaceFirst("[0]*$", "")

For example:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()).replaceFirst("[0]*$", "")
Dhrubajyoti Gogoi
  • 1,265
  • 10
  • 18
0

It could be a locale-specific issue you are getting. Try this:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
Denis Kulagin
  • 8,472
  • 17
  • 60
  • 129