Advertisement
Advertisement


Getting "unixtime" in Java


Question

Date.getTime() returns milliseconds since Jan 1, 1970. Unixtime is seconds since Jan 1, 1970. I don't usually code in java, but I'm working on some bug fixes. I have:

Date now = new Date();      
Long longTime = new Long(now.getTime()/1000);
return longTime.intValue();

Is there a better way to get unixtime in java?

2019/11/13
1
262
11/13/2019 1:58:19 PM

Accepted Answer

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;
2019/02/13
479
2/13/2019 3:34:22 PM


Source: https://stackoverflow.com/questions/732034
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]