115

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

0

7 Answers 7

179

java.sql.Timestamp extends java.util.Date. You can do:

String s = new SimpleDateFormat("MM/dd/yyyy").format(myTimestamp);

Or to also include time:

String s = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);
Sign up to request clarification or add additional context in comments.

5 Comments

That'll work, but beware since SimpleDateFormat is not thread-safe.
Just a small reminder that if SimpleDateFormat object is a local-scoped object (it is created and used only inside a method), then it is thread-safe, since stack on which it will reside is inherently "thread-safe" (as it belongs to a single thread).
To include time you will need to use SimpleDateFormat("MM/dd/yyyy hh:mm") or something similar
to make it complete for those who needs it, String S = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(myTimestamp);
java.text.SimpleDateFormat for those that have an IDE acting dumb on them.
33

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

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

EDIT:
please see the documentation of Formatter to know what TD and TT means: click on java.util.Formatter

The first 'T' stands for:

't', 'T'    date/time   Prefix for date and time conversion characters.

and the character following that 'T':

'T'     Time formatted for the 24-hour clock as "%tH:%tM:%tS".
'D'     Date formatted as "%tm/%td/%ty". 

4 Comments

This is the best answer, according to me. No superfluous object is created just for converting the timestamp to a string.
Now it should be clear where to find the documentation and what it means
Very elegant. Just to be clear, the formatting produced by the example here looks like 05/30/17 00:39:18.
@Noumenon thanks, that was the format "to my liking" as the question demanded [:-)
10

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

Comments

10

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 get 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).

2 Comments

Good warning. But very easy to address - don't share SimpleDateFormat instances by storing them in session scope / instance variables / static context and then accessing them from multiple threads. Just create a new SimpleDateFormat() within your method and discard it after use. That is threadsafe.
Of course if you really want to store/share SimpleDateFormat instance, then synchronise access: synchronized(simpleDateFormatInstance) {s = simpleDateFormatInstance.format(myTimeStamp)} OR create a custom extension of SDF class, and do this automatically within the format method.
2

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.

Comments

0

java.time

I am providing the modern answer. The Timestamp class is a hack on top of the already poorly designed java.util.Date class and is long outdated. I am assuming, though, that you are getting a Timestamp from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant and do further processing from there.

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.GERMAN);
    
    Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
    
    ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
            .atZone(ZoneId.systemDefault());
    String desiredFormat = dateTime.format(formatter);
    
    System.out.println(desiredFormat);

Output in my time zone:

07.09.2019 23:02:03

Pick how long or short of a format you want by specifying FormatStyle.SHORT, .MEDIUM, .LONG or .FULL. Pick your own locale where I put Locale.GERMAN. And pick your desired time zone, for example ZoneId.of("Europe/Oslo"). A Timestamp is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp comes from a database value of type timestamp without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault() is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime using oldfashionedTimestamp.toLocalDateTime() and then format the LocalDateTime in the same way as I did with the ZonedDateTime.

Comments

-15

String timeFrSSHStr = timeFrSSH.toString();

Comments

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.