Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time conversion in java

How can I convert unix time in java ?

Get this :

~#>date -d @1305176400
Thu May 12 00:00:00 CDT 2011

But in java

like image 289
London Avatar asked Oct 22 '25 18:10

London


2 Answers

String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
                  .format(new java.util.Date (epoch*1000));

See: http://www.epochconverter.com/

like image 165
Aidanc Avatar answered Oct 25 '25 07:10

Aidanc


java.time

In 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.

Solution using modern date-time API

You can get the desired result with following steps:

  1. Use Instant#ofEpochSecond to create an instance of Instant from epoch seconds.
  2. Convert the Instant into a ZonedDateTime by applying ZoneId.of("America/Chicago").
  3. Use a 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

Avoid using abbreviations for time zone ID

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.

like image 42
Arvind Kumar Avinash Avatar answered Oct 25 '25 06:10

Arvind Kumar Avinash