How do I formate a java.sql Timestamp to my liking ? ( to a string, for display purposes)
If you're using MySQL and want the database itself to perform the conversion, use this:
If you prefer to format using Java, use this:
SimpleDateFormat dateFormat = new SimpleDateFormat("M/dd/yyyy");
dateFormat.format( new Date() );
java.sql.Timestamp
extends java.util.Date
. Did you want something like:
String S = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);
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.
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).
Use String.format (or java.util.Formatter):
Timestamp timestamp = ...
String.format("%1$TD %1$TT", timestamp)