Java 8+
The most appropriate type to prase 1997-02-14T00:00:00.0000000+05:30 into is OffsetDateTime
. Note that java.time
API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter
to parse a date-time string which is already in ISO 8601 format.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
class Main {
public static void main(String[] args) {
String strDateTime = "1997-02-14T00:00:00.0000000+05:30";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
// Technically, you can also parse it into a ZonedDateTime but a ZonedDateTime
// is supposed to contain ZoneId along with ZoneOffset
System.out.println(ZonedDateTime.parse(strDateTime));
// With Java 12+, it is also possible to parse it into an Instant
System.out.println(Instant.parse(strDateTime));
}
}
Output:
1997-02-14T00:00+05:30
1997-02-14T00:00+05:30
1997-02-13T18:30:00Z
Learn more about the modern Date-Time API from Trail: Date Time.
Just for the sake of completeness
The java.util
Date-Time API and their formatting API, SimpleDateFormat
are outdated and error-prone. Since the release of Java-8 (Mar 2014), it is highly recommended to stop using them completely and switch to the modern Date-Time API. However, for any reason, if you want to stick to the legacy API, you can use SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX")
to parse your string.
class Main {
public static void main(String[] args) throws ParseException {
String strDateTime = "1997-02-14T00:00:00.0000000+05:30";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXX");
Date date = sdf.parse(strDateTime);
System.out.println(date);
}
}
Output:
Thu Feb 13 18:30:00 GMT 1997
+05:30
is not a time zone. That text is an offset from UTC. A time zone has a name in format ofContinent/Region
such asEurope/Paris
orAsia/Kolkata
. – Doiron+05:30
with a COLON character (:
) versus+0530
. Quite the opposite, as I have seen multiple libraries that expect the COLON character to be present despite the international standard ISO 8601 making it optional. So I recommend always including the COLON. – Doiron