Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix epoch time to Java Date object

I have a string containing the UNIX Epoch time, and I need to convert it to a Java Date object.

String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
  Date expiry = df.parse(date);
 } catch (ParseException ex) {
  ex.getStackTrace();
}

The marked line is where I'm having trouble. I can't work out what the argument to SimpleDateFormat() should be, or even if I should be using SimpleDateFormat().

like image 448
Xenph Yan Avatar asked Feb 11 '09 00:02

Xenph Yan


People also ask

How do I convert epoch to date?

Because our Epoch time is specified in milliseconds, we may convert it to seconds. To convert milliseconds to seconds, first, divide the millisecond count by 1000. Later, we use DATEADD() to add the number of seconds since the epoch, which is January 1, 1970 and cast the result to retrieve the date since the epoch.

How do I convert epoch time to manual date?

You can take an epoch time divided by 86400 (seconds in a day) floored and add 719163 (the days up to the year 1970) to pass to it. Awesome, this is as manual as it gets.

What is epoch date format java?

This code shows how to use a java.text.SimpleDateFormat to parse a java.util.Date from a String: String str = "Jun 13 2003 23:11:52.454 UTC"; SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS zzz"); Date date = df.parse(str); long epoch = date.getTime(); System.out.println(epoch); // 1055545912454.

What is Unix timestamp in java?

The UNIX timestamp (also known as POSIX time or EPOCH time) is a way to compute time as a running total of seconds that have elapsed since Thursday, 1 January 1970, 00:00:00 Coordinated Universal Time (UTC), minus the number of leap seconds that have elapsed since then.


2 Answers

How about just:

Date expiry = new Date(Long.parseLong(date)); 

EDIT: as per rde6173's answer and taking a closer look at the input specified in the question , "1081157732" appears to be a seconds-based epoch value so you'd want to multiply the long from parseLong() by 1000 to convert to milliseconds, which is what Java's Date constructor uses, so:

Date expiry = new Date(Long.parseLong(date) * 1000); 
like image 57
Marc Novakowski Avatar answered Sep 28 '22 04:09

Marc Novakowski


Epoch is the number of seconds since Jan 1, 1970..

So:

String epochString = "1081157732";
long epoch = Long.parseLong( epochString );
Date expiry = new Date( epoch * 1000 );

For more information: http://www.epochconverter.com/

like image 20
Ryan Emerle Avatar answered Sep 28 '22 04:09

Ryan Emerle