javadatetimejodatimelocaldatedatetime-parsing

Java LocalDate parser does not take hours, minutes, seconds into account


I want to parse DateTime from a string. Here is my code:

String dateStr = "2016-08-18T14:44:56.225Z"
final String Pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
final DateTimeFormatter dtf = DateTimeFormat.forPattern(Pattern);
LocalDate dt = dtf.parseLocalDate(dateStr);

Then I only receive Year, Month and Day (2016-08-18) from the code above. I cannot get Hours, Minutes and Seconds.

Did anyone get this problem before? How did you solve that? I use Java 7 and Joda-Time.


Solution

  • Use LocalDateTime to get time, too:

    String dateStr = "2016-08-18T14:44:56.225Z"
    final String Pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
    final DateTimeFormatter dtf = DateTimeFormat.forPattern(Pattern);
    LocalDateTime dt = dtf.parseLocalDateTime(dateStr);
    

    You are also ignoring the time zone (UTC/Zulu in this case - the Z at the end) - make sure if you really want to do this.