tl;dr
No need for System.currentTimeMillis();
. Use java.time classes.
LocalTime.now(
ZoneId.of( "America/Montreal" )
)
.truncatedTo(
ChronoUnit.SECONDS
)
.toString()
12:34:56
java.time
The modern approach uses the java.time classes. Never use the terrible Date
and Calendar
classes.
To get the current time-of-day requires a time zone. For any given moment, the time-of-day (and the date) vary around the globe by zone.
ZoneId z = ZoneId.of( "Australia/Sydney" ) ;
Capture the current time of day as seen in the wall-clock time used by the people of that particular region, that time zone. Obtain a LocalTime
object.
LocalTime lt = LocalTime.now( z ) ;
If you want UTC rather than a particular zone, pass the ZoneOffset.UTC
constant.
Apparently you want to track the time-of-day to the whole second. So let’s lop off the fractional second.
LocalTime lt = LocalTime.now( z ).truncatedTo( ChronoUnit.SECONDS ) ;
Generate text in standard ISO 8601 format by calling toString
.
String output = lt.toString() ;
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?
