tl;dr
ZonedDateTime.of(
LocalDate.of( 2015 , Month.JANUARY , 8 ) ,
LocalTime.of( 7 , 13 , 0 ) ,
ZoneId.of( "Africa/Tunis" )
)
.toInstant()
.toEpochMilli()
1420697580000
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes. So much easier and cleaner now.
Your code is ambiguous, as you do not address the crucial issue of time zone. As you did not specify a time zone explicitly, your JVM’s current default time zone will be applied implicitly. I strongly recommend always specifying your desired/expected time zone.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter pseudo-zones such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
LocalDate ld = LocalDate.of( 2015 , Month.JANUARY , 8 ) ;
LocalTime lt = LocalTime.of( 7 , 13 , 0 ) ;
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
You could use a combo factor method, alternatively.
ZonedDateTime zdt = ZonedDateTime.of( 2015 , Month.JANUARY , 8 , 7 , 13 , 0 , 0 , ZoneId.of( "Pacific/Auckland" ) ) ;
I generally recommend against tracking date-time as a count-from-epoch. But it seems to be requirement in your case.
First we can extract a Instant
, a moment in UTC. 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 = zdt.toInstant() ; // Convert from a zoned value to a UTC value.
You can then ask for the count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00:00Z. Beware of possible data loss, as any microseconds or nanoseconds in the Instant
will be ignored when reporting mere milliseconds.
long millis = instant.toEpochMilli() ; // Count of milliseconds since 1970-01-01T00:00:00Z.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.