I can convert a unix timestamp to a Date()
object by putting the long
value into the Date()
constructor. For eg: I could have it as new Date(1318762128031)
.
But after that, how can I get back the unix timestamp from the Date()
object?
To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.
If you'd like to calculate the difference between the timestamps in seconds, multiply the decimal difference in days by the number of seconds in a day, which equals 24 * 60 * 60 = 86400 , or the product of the number of hours in a day, the number of minutes in an hour, and the number of seconds in a minute.
Unix time is a way of representing a timestamp by representing the time as the number of seconds since January 1st, 1970 at 00:00:00 UTC. One of the primary benefits of using Unix time is that it can be represented as an integer making it easier to parse and use across different systems.
getTime()
retrieves the milliseconds since Jan 1, 1970 GMT passed to the constructor. It should not be too hard to get the Unix time (same, but in seconds) from that.
To get a timestamp
from Date()
, you'll need to divide getTime()
by 1000
, i.e. :
Date currentDate = new Date(); currentDate.getTime() / 1000; // 1397132691
or simply:
long unixTime = System.currentTimeMillis() / 1000L;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With