Daniel Morgan
Daniel Morgan

Reputation: 772

How to retrieve date from database using java

I need to retrieve the date and time from a database. My code correctly retrieves the date and time but when I use toString() it adds a ".0" to the end of the time. How can I avoid this?

IE: date on database is 2013-03-05 11:05:25

When I retrieve it and try to convert it to a String it becomes 2013-03-05 11:05:25.0

 r.getTimestamp("mydate").toString();

Upvotes: 0

Views: 12577

Answers (3)

Sean F
Sean F

Reputation: 2390

Use SimpleDateFormat to display the date in any fashion you want

String output = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(r.getTimestamp("mydate"));

This should display it how you are after.

EDIT:

You have said your method is not returning the object as a timestamp or date, you need to put it into a date format first to use SimpleDateFormat:

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String in = r.getTimestamp("mydate"));
Date d = sdf.parse(in);

Upvotes: 2

Breavyn
Breavyn

Reputation: 2242

If you want to actually remove the ".0" you could just do this. Where "s" is the string object with the extra 2 characters.

s = s.substring(0, s.length() - 2);

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502336

Don't think about the value on the database as being a string value at all. Think of it being a point in time. (I'm assuming it really is a TIMESTAMP field or something similar.)

If you want to format it in a particular way, do so - but 2013-03-05 11:05:25 is the same point in time as 2013-03-05 11:05:25.0... it's just using a different string representation.

Upvotes: 3

Related Questions