How can I convert unix time in java ?
Get this :
~#>date -d @1305176400
Thu May 12 00:00:00 CDT 2011
But in java
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new java.util.Date (epoch*1000));
See: http://www.epochconverter.com/
java.timeIn March 2014, Java 8 introduced the modern, java.time date-time API which supplanted the error-prone legacy java.util date-time API. Any new code should use the java.time API.
You can get the desired result with following steps:
Instant#ofEpochSecond to create an instance of Instant from epoch seconds.Instant into a ZonedDateTime by applying ZoneId.of("America/Chicago").DateTimeFormatter instantiated with the required pattern/format to format the resulting ZonedDateTime.Demo:
class Main {
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z uuuu",
Locale.ENGLISH);
public static void main(String args[]) {
long epochSeconds = 1305176400L;
Instant instant = Instant.ofEpochSecond(epochSeconds);
ZoneId zoneId = ZoneId.of("America/Chicago");
ZonedDateTime zdt = instant.atZone(zoneId);
System.out.println(zdt);
// Representation in a custom format
System.out.println(zdt.format(formatter));
}
}
Output:
2011-05-12T00:00-05:00[America/Chicago]
Thu May 12 00:00:00 CDT 2011
Online Demo
Given below is an excerpt from the legacy TimeZone documentation:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
So, instead of the abbreviated time zone ID, you should use the full form e.g. by using DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss VV uuuu", Locale.ENGLISH), you will get Thu May 12 00:00:00 America/Chicago 2011 as the output.
Learn more about the modern Date-Time API from Trail: Date Time.
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