0

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();
1
  • 1
    I believe you want to use SimpleDateFormat to construct a date as you like Commented Mar 5, 2013 at 0:58

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

yeah it is the same but wy is it adding the .0 to the end of it?
@DanielMorgan: That's just how Timestamp.toString() works. It's not "adding" it - it's just using a format of "yyyy-mm-dd hh:mm:ss.fffffffff" as documented.
Jon is absolutly correct have a look at the toString doco for timestamp - docs.oracle.com/javase/1.4.2/docs/api/java/sql/Timestamp.html
2

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);

2 Comments

I did it but it shows an error : cannot format given Object as a Date
what does r.getTimestamp("mydate")) return? this would work if it returns a timestamp (i just ran it on a timestamp and it works). if it is returning an object should you cast the object to a timestamp?
1

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);

2 Comments

thanks but I need to know how to avoid it not how to remove it
substring manipulation isn't a particularly nice way to do things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.