Since question is tagged java-8
use java.time
API.
UPDATE: For version 4 of question where 2018-06-06T11:30:00-05:00
was added.
To parse 1528302600000
, you parse it into a long
, then use Instant.ofEpochMilli()
.
To parse a format like 2018-06-06T11:30:00-05:00
, you can using OffsetDateTime
or ZonedDateTime
. Both can also parse 2018-06-06T16:30:00Z
.
To change the time zone specifically to a particular offset like GMT+5:30
, use ZoneOffset
, e.g. ZoneOffset.of("+05:30")
, or ZoneId
, e.g. ZoneId.of("GMT+05:30")
.
Note 1: GMT+5:30
is not valid.
Note 2: To change to the time zone of a region, honoring Daylight Savings Time, use e.g. ZoneId.of("Asia/Kolkata")
.
To parse all 3 input formats, and even support the extended format like 2018-06-06T11:30-05:00[America/Chicago]
, use ZonedDateTime
, with special handling for the epoch number.
public static ZonedDateTime parseToZone(String text, ZoneId zone) {
if (text.indexOf('-') == -1)
return Instant.ofEpochMilli(Long.parseLong(text)).atZone(zone);
return ZonedDateTime.parse(text).withZoneSameInstant(zone);
}
The caller can then decide if only the offset, not the full time zone, should be used, by converting it to OffsetDateTime
using toOffsetDateTime()
.
Test
ZoneId india = ZoneId.of("Asia/Kolkata");
System.out.println(parseToZone("2018-06-06T16:30:00Z", india));
System.out.println(parseToZone("2018-06-06T11:30:00-05:00", india));
System.out.println(parseToZone("1528302600000", india));
System.out.println(parseToZone("1528302600000", india).toOffsetDateTime());
Output
2018-06-06T22:00+05:30[Asia/Kolkata]
2018-06-06T22:00+05:30[Asia/Kolkata]
2018-06-06T22:00+05:30[Asia/Kolkata]
2018-06-06T22:00+05:30
Original Answer
Use the parse()
method with 2018-06-06T16:30:00Z
.
Use the ofEpochMilli()
method with 1528302600000
.
Then use atZone()
to convert to your desired time zone.
Demo
Instant instant1 = Instant.parse("2018-06-06T16:30:00Z");
Instant instant2 = Instant.ofEpochMilli(1528302600000L);
ZoneId india = ZoneId.of("Asia/Kolkata");
ZonedDateTime date1 = instant1.atZone(india);
ZonedDateTime date2 = instant2.atZone(india);
System.out.println(instant1);
System.out.println(instant2);
System.out.println(date1);
System.out.println(date2);
Output
2018-06-06T16:30:00Z
2018-06-06T16:30:00Z
2018-06-06T22:00+05:30[Asia/Kolkata]
2018-06-06T22:00+05:30[Asia/Kolkata]
To print the result in human format, use a DateTimeFormatter
.
DateTimeFormatter indiaFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.forLanguageTag("en-IN"));
DateTimeFormatter hindiFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.forLanguageTag("hi-IN"));
System.out.println(date1.format(indiaFormatter));
System.out.println(date1.format(hindiFormatter));
Output
6 June 2018 at 10:00:00 PM IST
6 जून 2018 को 10:00:00 अपराह्न IST