java.time
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
A sample solution using java.time
, the modern Date-Time API: You can use ZonedDateTime#withZoneSameInstant
for this purpose.
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZoneId sourceZone = ZoneId.of("Europe/Berlin");
ZonedDateTime zdtSource = ZonedDateTime.now(sourceZone);
System.out.println(zdtSource);
ZoneId targetZone = ZoneId.of("America/New_York");
ZonedDateTime zdtTarget = zdtSource.withZoneSameInstant(targetZone);
System.out.println(zdtTarget);
}
}
Output from a sample run:
2021-08-10T20:06:24.023038+02:00[Europe/Berlin]
2021-08-10T14:06:24.023038-04:00[America/New_York]
ONLINE DEMO
What if I need OffsetDateTime
?
You can use ZonedDateTime#toOffsetDateTime
to get OffsetDateTime
out of a ZonedDateTime
object e.g.
OffsetDateTime odtTarget = zdtTarget.toOffsetDateTime();
Note: For any reason, if you need to convert this object of ZonedDateTime
to an object of java.util.Date
, you can do so as follows:
Date date = Date.from(zdtTarget.toInstant());
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.