java.time
The root cause of the problem is using wrong symbols
Y
(which specifies week-based-year) instead of y
(which specifies year-of-era)
D
(which specifies day-of-year) instead of d
(which specifies day-of-month).
h
(which specifies clock-hour-of-am-pm) instead of H
(which specifies hour-of-day).
Check the documentation page
to learn more about these symbols.
Also, note that the legacy date-time API (java.util
date-time types and their formatting API, SimpleDateFormat
) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time
, the modern date-time API*.
Solution using the modern API:
The modern date-time API is based on ISO 8601 and does not require you to use a DateTimeFormatter
object explicitly as long as the date-time string conforms to the ISO 8601 standards. Your date-time string conforms to ISO 8601 standards (or the default format used by OffsetDateTime#parse
).
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strDateTime = "2015-06-16T14:58:48Z";
OffsetDateTime odt = OffsetDateTime.parse(strDateTime);
System.out.println(odt);
// ########################Extract time information########################
LocalTime time = odt.toLocalTime();
// You can also get it as time.getHour()
// Extract other units in a similar way
int hour = odt.getHour();
// Also using time.format(DateTimeFormatter.ofPattern("a", Locale.ENGLISH));
String amPm = odt.format(DateTimeFormatter.ofPattern("h a", Locale.ENGLISH));
System.out.println(time);
System.out.println(hour);
System.out.println(amPm);
}
}
Output:
2015-06-16T14:58:48Z
14:58:48
14
2 PM
Note:
- The
Z
in the output is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC
timezone (which has the timezone offset of +00:00
hours).
- For any reason, if you need to convert this object of
OffsetDateTime
to an object of java.util.Date
, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the 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.