Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting unix timestamp from Date()

Tags:

java

date

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?

like image 743
Carven Avatar asked Oct 16 '11 12:10

Carven


People also ask

How do you find the timestamp in Unix?

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.

How do you calculate a timestamp from a date?

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.

What is Unix timestamp for a date?

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.


2 Answers

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.

like image 199
jackrabbit Avatar answered Oct 22 '22 01:10

jackrabbit


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; 
like image 31
Pedro Lobito Avatar answered Oct 22 '22 01:10

Pedro Lobito