Search Stack Overflow before posting. This has been addressed many times already. And read the Oracle Tutorial. So briefly here…
tl;dr
ZonedDateTime.of( 2018 , 1 , 23 , 12 , 34, 56 , 0 , ZoneId.of( “Asia/Kolkata” ) )
.withZoneSameInstant( ZoneId.of( “Europe/Berlin” ) )
java.time
Use modern java.time classes that supplanted the troublesome legacy date-time classes you used.
ZonedDateTime
Pass those arguments to ZonedDateTime.of
rather than legacy Calendar
.
ZoneId
For the time zone, pass ZoneId
object, not legacy TimeZone
.
Never use 3-4 letter pseudo-zones like “PST” and “CST” and “IST”. Always use proper time zone names in continent/region format such as America/Los_Angeles
or Africa/Tunis
.
ZonedDateTime zdt = ZonedDateTime.of( 2018 , 1 , 23 , 12 , 34, 56 , 0 , ZoneId.of( “Asia/Kolkata” ) ) ;
Adjust into another zone. Same moment, same point on the timeline, different wall-clock time.
ZonedDateTime zdt2 = zdt.withZoneSameInstant( ZoneId.of( “Europe/Berlin” ) ) ;
DateTimeFormatter
Generate a String in standard ISO 8601 format by calling ZonedDateTime::toString
. For other formats use DateTimeFormatter
class.
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.