Epoch and Date Time Conversion in Java

Java is a popular object oriented programming language. It is intended to let developers write once, run anywhere compiled Java code that run on all platforms that support Java without the need for recompilation. Java has java.time package that work with date and time. So with Java, we we can easily handle epoch or Unix timestamp conversion into human readable dates or can convert human readable dates to Unix timestamp.

Here we will explain Java classes and methods to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.

Get current epoch or Unix timestamp in Java

We can get the current epoch or timestamp using Date class from Java. It will returns the current epoch in the number of seconds.

Date date = new Date();
long unixTime = date.getTime() / 1000L;
System.out.println(unixTime);


Output
1585990763

Convert epoch or Unix timestamp to human readable date in Java

We can convert the epoch or timestamp to readable date format using Java Date() class. The function formats and return epoch or timestamp to human readable date and time.

Date date = new Date(1585990763);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String myDate = format.format(date);

Output
2020-04-05:05:36::40

Convert date to epoch or unix timestamp in Java

We can convert human readable date to timestamp using Java Date class. The function convert English textual datetime into a Unix timestamp.

String myDate = "2020-04-05 05:36:40";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = dateFormat.parse(myDate);
long epoch = date.getTime();
System.out.println(epoch);

Output
1585990763


More about date time in Java