If you are on Java 8 or beyond, you may use LocalDateTime
, as shown below.
Edit
Based on the comments from @Andreas and @OleV.V., I thought of compiling 4 ways for easy reference. 2 of these use OffsetDateTime
and 2 use @Sriram's ZonedDateTime
answer. Also, based on whether one has a string at the start or a LocalDateTime
.
String string = "2020-02-10T22:55:13-08:00";
DateTimeFormatter inF = DateTimeFormatter.ISO_DATE_TIME;
String desiredZoneId = "Z";
int desiredOffset = 0;
DateTimeFormatter toF = DateTimeFormatter.ofPattern( "h:mm a" );
LocalDateTime ldt = LocalDateTime.parse(string.trim(), inF );
/* Prints -> "ldt.atOffset: 6:55 AM" */
/* 1. If one already has a LocalDateTime. Drawback: One needs to know the offset in the time string. */
System.out.println( "ldt.atOffset: " + ldt.atOffset( ZoneOffset.ofHours( -8 ) ).withOffsetSameInstant( ZoneOffset.ofHours( desiredOffset ) ).format( toF ) );
/* Prints -> "ldt.atZone: 6:55 AM" */
/* 2. If one already has a LocalDateTime. Drawback: One needs to know the offset in the time string. */
System.out.println( "ldt.atZone: " + ldt.atZone( ZoneId.of( "-08:00" ) ).withZoneSameInstant( ZoneId.of( desiredZoneId ) ).format( toF ) );
/* Prints -> "odt: 6:55 AM" */
/* 3. Using OffsetDateTime. */
OffsetDateTime odt = OffsetDateTime.parse( string, inF );
System.out.println( "odt: " + odt.withOffsetSameInstant( ZoneOffset.ofHours( desiredOffset ) ).format( toF ) );
/* Prints -> "zdt: 6:55 AM" */
/* 4. Using ZonedDateTime. */
String zdt = ZonedDateTime.parse( string, DateTimeFormatter.ISO_DATE_TIME )
.withZoneSameInstant( ZoneId.of( desiredZoneId ) ).format( toF );
System.out.println( "zdt: " + zdt );