fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.lang.*;
  4. import java.time.OffsetDateTime;
  5. import java.time.chrono.IsoChronology;
  6. import java.time.format.DateTimeFormatter;
  7. import java.time.format.DateTimeParseException;
  8. import java.time.format.ResolverStyle;
  9.  
  10. /* Name of the class has to be "Main" only if the class is public. */
  11. class Ideone
  12. {
  13. public static void main (String[] args) throws java.lang.Exception
  14. {
  15. DateTimeFormatter smartFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssZ")
  16. .withChronology(IsoChronology.INSTANCE);
  17. DateTimeFormatter strictFormatter = smartFormatter.withResolverStyle(ResolverStyle.STRICT);
  18. String inputString = "20140726080320+0400";
  19.  
  20. OffsetDateTime parsedDateTime = OffsetDateTime.parse(inputString, smartFormatter);
  21. System.out.println("Parsed smart: " + parsedDateTime);
  22.  
  23. String formattedStrict = parsedDateTime.format(strictFormatter);
  24. System.out.println("Formatted strict: " + formattedStrict);
  25. System.out.println("Is string equal? " + formattedStrict.equals(inputString));
  26.  
  27. try {
  28. OffsetDateTime.parse(formattedStrict, strictFormatter);
  29. } catch (DateTimeParseException dtpe) {
  30. System.out.println("Strict formatter cannot parse the string it has produced:");
  31. System.out.println(dtpe);
  32. }
  33. }
  34. }
Success #stdin #stdout 0.14s 4575232KB
stdin
Standard input is empty
stdout
Parsed smart:     2014-07-26T08:03:20+04:00
Formatted strict: 20140726080320+0400
Is string equal?  true
Strict formatter cannot parse the string it has produced:
java.time.format.DateTimeParseException: Text '20140726080320+0400' could not be parsed: Unable to obtain OffsetDateTime from TemporalAccessor: {YearOfEra=2014, MonthOfYear=7, DayOfMonth=26, OffsetSeconds=14400},ISO resolved to 08:03:20 of type java.time.format.Parsed