tl;dr
myJavaUtilDate // Some `java.util.Date` object. This troublesome class is obsolete.
.toInstant() // Convert from terrible legacy class to modern *java.time* class. Both represent a moment in UTC, always UTC.
.atZone( // Adjust from `Instant` in UTC to a `ZonedDateTime` in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Asia/Kolkata" ) // Specify time zone with `Continent/Region` name, never 3-4 letter pseudo-zone.
) // Returns a `ZonedDateTime` object.
.toString() // Generate a String in standard ISO 8601 format extended to append name of zone.
java.time
So you have a java.util.Date
object in hand? Convert from that terrible old outmoded class to its modern replacement, java.time.Instant
.
Instant instant = myJavaUtilDate.toInstant() ;
Apply a time zone (ZoneId
) to get a ZonedDateTime
.
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( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate a string is standard ISO 8601 format wisely extended to append the name of the time zone in square brackets, call toString
.
String output = zdt.toString() ; // Standard ISO 8601 format, extended by appending name of zone.
For other formats, search Stack Overflow for DateTimeFormatter
class. This has been discussed many many times already.
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.