TimeZone and Date Conversion using Java 8 APIs:
ISO8601 to GMT Timestamp :
import java.sql.Timestamp;
import java.time.ZoneId;
import
java.time.ZonedDateTime;
import java.util.TimeZone;
public class ConvertUtilTest {
public static void main(String[] args) {
ConvertUtilTest
convertUtilTest = new ConvertUtilTest();
convertUtilTest.convertIso8601ToGmtTimestamp();
}
public void convertIso8601ToGmtTimestamp()
{
String
iso8601 = "2011-12-03T11:15:30+09:00";
Timestamp result = ConvertDate.convertGmtTimestampFromIso8601(iso8601, "Asia/Tokyo");
System.out.println("
convertIso8601ToGmtTimestamp : "+result);
}
}
--------------------------- ConvertDate.java---------------
public class ConvertDate {
public static Timestamp convertGmtTimestampFromIso8601(String
iso8061DateTime, String currentTimeZone) {
ZonedDateTime
zonedDateTime = convertZonedDateTimeFromIso8601(iso8061DateTime, currentTimeZone);
return Timestamp.valueOf(LocalDateTime.ofInstant(zonedDateTime.toInstant(),
ZoneOffset.UTC));
}
public static ZonedDateTime convertZonedDateTimeFromIso8601(String iso8061DateTime, String currentTimeZone) {
ZonedDateTime
zonedDateTime = null;
if (iso8061DateTime != null) {
Boolean
hasOffset = null;
LocalDateTime
localDateTime = null;
try {
// Getting
OffsetDateTime to check that provided
// ISO string has
offset OR not.
OffsetDateTime
offsetDateTime = OffsetDateTime.parse(iso8061DateTime);
hasOffset = Boolean.TRUE;
}
catch
(DateTimeParseException dte) {
try {
hasOffset = Boolean.FALSE;
localDateTime = LocalDateTime.parse(iso8061DateTime);
}
catch
(DateTimeParseException dte2) {
}
}
if (!hasOffset) {
if (currentTimeZone != null && !currentTimeZone.isEmpty()) {
zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of(currentTimeZone));
}
}
else {
zonedDateTime = ZonedDateTime.parse(iso8061DateTime);
}
}
return zonedDateTime;
}
}
Output:
More Conversion:
convertIso8601ToGmtTimestamp : 2011-12-03 02:15:30.0
No comments:
Post a Comment