tl;dr
Use java.time classes.
OffsetDateTime // Represent a moment as a date, a time-of-day, and an offset-from-UTC (a number of hours, minutes, seconds) with a resolution as fine as nanoseconds.
.now( // Capture the current moment.
ZoneOffset.UTC. // Specify your desired offset-from-UTC. Here we use an offset of zero, UTC itself, predefined as a constant.
) // Returns a `OffsetDateTime` object.
.format( // Generate text in a `String` object representing the date-time value of this `OffsetDateTime` object.
DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US )
) // Returns a `String` object.
2018-09-27T05:39:41.023987+00:00
Or, use Z
for UTC.
Instant.now().toString()
2018-09-27T05:39:41.023987Z
java.time
The modern approach uses the java.time that supplanted the terrible old date-time classes.
Specifically:
- Use
Instant
or OffsetDateTime
instead of java.util.Date
.
- Use
DateTimeFormatter
instead of `SimpleDateFormat.
Get the current time in UTC. We use the OffsetDateTime
class rather than Instant
for more flexible formatting when generating text.
ZoneOffset offset = ZoneOffset.UTC;
OffsetDateTime odt = OffsetDateTime.now( offset );
Define a formatting pattern to match your desired output. Note that the built-in formatting patterns use Z
as standard shorthand for +00:00
. The Z
means UTC and is pronounced “Zulu”. This Zulu time format is quite common. I suggest using such formats with Z
. But you asked explicitly for the long version of an offset-from-UTC of zero, so we must use a custom DateTimeFormatter
object.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd'T'HH:mm:ss.SSSSSSxxxxx" , Locale.US );
String output = odt.format( f );
2018-09-27T05:39:41.023987+00:00
FYI, the formats discussed here comply with the ISO 8601 standard.
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?