Vasil Valchev Vasil Valchev - 2 months ago 4x
Java Question

Convert System.currentTimeMillis() in to current time

I have problem to understand how

works, and how can I use it.

long currentTime = System.currentTimeMillis(); // -1293027002
Date currentDate = new Date(currentTime);

SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy:HH:mm:ss");


will result


This is year
, I expect

What is the problem here?


As Java documentation says, currentTimeMillis will return the time difference from January 1, 1970 UTC and it depends on the OS. An alternative for you if you want the time in millis would be to get it from new instances of Date that will return the current time by default:

Date current = new Date()
long currentInMillis = current.getTime()

Edit 1:

As Java documentation says:

Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.