Convert unix time stamp to date in java

bigData picture bigData · Jul 2, 2013 · Viewed 143.6k times · Source

How can I convert minutes from unix time stamp to date and time in java. For example, time stamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.

I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.

Edit : Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.

Answer

David Hofmann picture David Hofmann · Jul 2, 2013

You can use SimlpeDateFormat to format your date like this:

long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L); 
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4")); 
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

  • Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)