Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Timestamps in Java

Tags:

java

date

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?

like image 747
Craig H Avatar asked Sep 24 '08 19:09

Craig H


People also ask

How do you create a timestamp in Java?

To get the current timestamp in Java, we can use the Timestamp class. Since this class does not have a default constructor, so we pass the time in milliseconds. We use the currentTimeMillis() method of System class to get the time.

How do you format a date in Java?

String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); In the example above the String pattern is the pattern which will be used to format a date and the output will be generated in that pattern as “MM-dd-yyyy”.

What is T & Z in UTC time format?

The T is just a literal to separate the date from the time, and the Z means “zero hour offset” also known as “Zulu time” (UTC). If your strings always have a “Z” you can use: SimpleDateFormat format = new SimpleDateFormat( “yyyy-MM-dd'T'HH:mm:ss).


3 Answers

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.

like image 50
Brendan Cashman Avatar answered Oct 22 '22 01:10

Brendan Cashman


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));
like image 28
Jay Avatar answered Oct 21 '22 23:10

Jay


Date instances are insufficient for some purposes.

Use Joda Time instead.

Joda time integrates with Hibernate and other databases.

like image 26
Maxim Avatar answered Oct 21 '22 23:10

Maxim