tl;dr
Instant.now()
.toString()
2017-01-23T12:34:56.123456789Z
UTC
Generally best to exchange data for date-time values in UTC (GMT). Let the receiver adjust into a desired time zone.
Instant
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = Instant.now() ;
String output = instant.toString() ; // Generate a String in standard ISO 8601 format.
2017-01-23T12:34:56.123456789Z
You can easily parse that string.
Instant instant = Instant.parse( "2017-01-23T12:34:56.123456789Z" ) ;
ISO 8601
The ISO 8601 standard defines clear easy-to-read easy-to-parse formats for textual representations of date-time values. These formats are ideal for data-exchange.
For a moment in UTC, that means the format seen in example above. The T
separates the date portion from the time of day portion. The Z
on the end is short for Zulu
and means UTC.
Locale
The Question mentions locale as if related to time zone. A Locale
has nothing to do with time zone. A Locale
specifies (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, and such.
A time zone is a history of changes to a region’s offset-from-UTC, tracking anomalies causing those changes such as Daylight Saving Time (DST).
Search Stack Overflow to learn more. This has already been covered many hundreds of times already. Search for classes such as ZoneId
, ZoneOffset
, ZonedDateTime
, Instant
, OffsetDateTime
, and DateTimeFormatter
. Read the Oracle Tutorial on the java.time classes.
ZonedDateTime zdt = instant.atZone( ZoneId.of( "Pacific/Auckland" ) ) ;
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.