Sunday 22 October 2017

Convert epoch to human readable format

In this post, I am going to explain how to convert epoch time to human readable format.

SimpleDateFormat class provides format method to convert given date into human readable format.

Step 1: Get Date instance from seconds.
Date date = new Date(seconds);

Step 2: Create instance of SimpleDateFormat class.
DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");

Step 3: Use the format method to convert given date into human readable form.
formatter.format(date);

Find the below working application.

Test.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Test {
 public static String getDateFromSeconds(long seconds) {
  Date date = new Date(seconds);
  DateFormat formatter = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
  return formatter.format(date);
 }

 public static void main(String args[]) {
  long timeInSeconds = 1508683954000l;

  String date = getDateFromSeconds(timeInSeconds);
  System.out.println(date);
 }
}

Output
2017.10.22 20:22:34

Below are some of the examples to format given date.

"K:mm a, z"
"EEE, d MMM yyyy HH:mm:ss Z"
"yyMMddHHmmssZ"
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
"yyyyy.MMMMM.dd GGG hh:mm aaa"
"hh 'o''clock' a, zzzz"
"yyyy.MM.dd G 'at' HH:mm:ss z"
"EEE, MMM d, ''yy"
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"
"YYYY-'W'ww-u"
"h:mm a"

You may like
Interview Questions

No comments:

Post a Comment