Craig H
Craig H

Reputation: 7989

Formatting Timestamps in Java

Is there a way to format a UTC time into any arbitrary string format I want in java? Basically I was thinking of having some class take the timestamp and I pass it is string telling it how I want it formated, and it returns the formatted string for me. Is there a way to do this?

Upvotes: 28

Views: 62057

Answers (4)

Brendan Cashman
Brendan Cashman

Reputation: 4928

The java.text.SimpleDateFormat class provides formatting and parsing for dates in a locale-sensitive manner.

The javadoc header for SimpleDateFormat is a good source of detailed information. There is also a Java Tutorial with example usages.

Upvotes: 33

Maxim
Maxim

Reputation: 543

Date instances are insufficient for some purposes.

Use Joda Time instead.

Joda time integrates with Hibernate and other databases.

Upvotes: 4

Alex Miller
Alex Miller

Reputation: 70201

One gotcha to be aware of is that SimpleDateFormat is NOT thread-safe. Do not put it in a static field and use it from multiple threads concurrently.

Upvotes: 3

Jay
Jay

Reputation: 42632

The DateFormat class or SimpleDateFormat should get you there. For example, http://www.epochconverter.com/ lists the following example to convert a epoch time to human readable timestamp with Java:

String date = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));

Upvotes: 28

Related Questions