Convert Milliseconds to Date Java

Convert Milliseconds to Date Java

In Java coding, many times it is required to read the system time and at the same time convert the system time into objects of Date and Calendar etc. Following code illustrates.

Example on Convert Milliseconds to Date Java

Convert Milliseconds to Date Java
Output screen on Convert Milliseconds to Date Java

There are two ways of getting system time in milliseconds – using currentTimeMillis() of System class and getTimeInMillis() of Calendar class. In the output, you can observe different outputs of milliseconds and is due to execution time of step-by-step. Regarding preference, better use currentTimeMillis() instead of getTimeInMillis() as getTimeInMillis() requires the creation of Calendar object, an extra work. currentTimeMillis() returns a long value just stored in a variable. Infact, the Date and Calendar classes use internally currentTimeMillis() to create Date and Calendar objects.

The static method, currentTimeMillis() of System class returns the time in milleseconds (in long data type) starting from 1st January, 1970 (known as Epoch time). The value returned can be converted into objects of Calendar, java.util.Date and java.sql.Date and java.sql.Timestamp as per code requirement.

To create Timestamp object

Infact, you can replace the following

with direct Date object without using currentTimeMillis()

as both gives the same output.

Another way of creating Date object is

Again it is round about fashion.

When to use what?

a) Use currentTimeMillis() when you require the milliseconds representation of current time.
b) Use Date when you require Date object representation of current time.
c) Use Calendar (with getInstance()) when you require Calendar object with time zone and locale specific details.

One thought on “Convert Milliseconds to Date Java

Leave a Reply

Your email address will not be published. Required fields are marked *