views:

5580

answers:

6

How do I formate a java.sql Timestamp to my liking ? ( to a string, for display purposes)

+1  A: 

If you're using MySQL and want the database itself to perform the conversion, use this:

DATE_FORMAT(date,format)

If you prefer to format using Java, use this:

java.text.SimpleDateFormat

SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );
DreadPirateShawn
+7  A: 

java.sql.Timestamp extends java.util.Date. Did you want something like:

String S = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);
ChssPly76
That'll work, but beware since SimpleDateFormat is not thread-safe.
Brian Agnew
+1  A: 

Use a DateFormat. In an internationalized application, use the format provide by getInstance. If you want to explicitly control the format, create a new SimpleDateFormat yourself.

erickson
A: 

To obtain Timestamp as a String:

yourStamp.toString();
pianoman
A: 

For this particular question, the standard suggestion of java.text.SimpleDateFormat works, but has the unfortunate side effect that SimpleDateFormat is not thread-safe and can be the source of particularly nasty problems since it'll corrupt your output in multi-threaded scenarios, and you won't any exceptions!

I would strongly recommend looking at Joda for anything like this. Why ? It's a much richer and more intuitive time/date library for Java than the current library (and the basis of the up-and-coming new standard Java date/time library, so you'll be learning a soon-to-be-standard API).

Brian Agnew
A: 

Use String.format (or java.util.Formatter):

Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)
Carlos Heuberger