tl;dr
Duration.between( todayStart , now ).toMillis()
Details
Get the current moment in the wall-clock time used by the people of a certain region (a time zone).
ZoneId z = ZoneId.of( “Africa/Tunis” ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
Get the first moment of the day. Do not assume this is 00:00:00. Let java.time determine.
ZonedDateTime todayStart = now.toLocalDate().atStartOfDay( z ) ;
Represent the delta between them, the span of time unattached to the timeline, as a Duration
.
Duration d = Duration.between( todayStart , now ) ;
A Duration
has a resolution of nanoseconds. That is finer than the milliseconds you desire. A convenience method will ignore any microseconds or nanoseconds for you.
long millisSinceStartOfToday = d.toMillis() ;
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.