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().
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.
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.
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.
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.
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);
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With