tl;dr
Instant.now()
.getEpochSecond()
1519944626
java.time
The modern approach uses the java.time classes.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.now() ; // Capture current moment in UTC.
Count-from-epoch
You can determine the number of whole seconds from the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. Beware of data loss: You are ignoring any fractional second that may be residing in your Instant
object’s value.
long secondsSinceEpoch = instant.getEpochSecond() ; // Ignores any fractional second in your `Instant`.
Parsing
Your can go the other direction, parsing such a count-from-epoch into an Instant
object.
Instant instant = Instant.ofEpochSecond( yourCountFromEpochGoesHere ) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.