tl;dr
ZonedDateTime // Represent a moment as seen in the wall-clock time used by the people of a particular region (a time zone).
.now( // Capture the current moment.
ZoneId.of( "America/New_York" ) // Specify the time zone through whose wall-clock time we want to perceive the current date and time.
) // Returns a `ZonedDateTime` object.
.toString() // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
2017-11-23T23:43:45-05:00[America/New_York]
ISO 8601
The ISO 8601 standard defines many practical formats for representing date-time values as human-readable text. The first chunk of your desired format is one such standard format:
2017-11-23T23:43:45-05:00
Your desired format extends standard format by appending the name of the time zone in square brackets.
2017-11-23T23:43:45-05:00[America/New_York]
That extended standard format is exactly the behavior of the ZonedDateTime::toString
method. You will find that class bundled with Java.
ZonedDateTime.now().toString() // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
Avoid legacy date-time classes
The SimpleDateFormat
class is part of the troublesome old date-time classes that were supplanted years ago by the java.time classes. Never use these awful legacy classes.
ZonedDateTime
Get the current moment as seen in the wall-clock time used by the people of a particular region (a 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 abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
Generate a String
object containing text in your desired format.
String output = zdt.toString() ; // Generate text in standard ISO 8601 format extended to append the name of the time zone in square brackets.
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.