As in your previous question I recommend you throw out the outdated classes SimpleDateFormat
and friends. The modern classes are generally so much more programmer friendly.
Let’s try an experiment:
String dateq = " Tue Feb 08 12:30:27 +0000 2011 ";
DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
Locale.FRENCH);
OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfFr);
Your exception message clearly shows there are spaces (or other invisible chars) in the beginning and end of your string, so I put them in my string too. Other than that your message just said that the date was unparseable, not why. In contrast, the above code gives java.time.format.DateTimeParseException: Text ' Tue Feb 08 12:30:27 +0000 2011 ' could not be parsed at index 0
. Index 0, that is where the first space is, so it’s already a bit more helpful.
My suggestion for removing the spaces:
dateq = dateq.trim();
This will work with all whitespace, not only space characters, and it will work if there are 0, 1, 2 or many of them. With this line inserted at the right place we get java.time.format.DateTimeParseException: Text 'Tue Feb 08 12:30:27 +0000 2011' could not be parsed at index 0
. It’s almost the same message! This time we see no space in the beginning of the string, but it still says the problem is at index 0. This is now where it says “Tue”. The message again is to the point because the problem with “Tue” is it’s English, and you gave a locale of Locale.FRENCH
. Having seen that, it’s not difficult:
System.out.println("date de la requete est " + dateq);
dateq = dateq.trim();
DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
Locale.ENGLISH);
OffsetDateTime date1 = OffsetDateTime.parse(dateq, dtfEng);
System.out.println("new date: " + date1);
This prints:
date de la requete est Tue Feb 08 12:30:27 +0000 2011
new date: 2011-02-08T12:30:27Z
If you don’t know in advance whether you will have a date in English or French, just try both:
dateq = dateq.trim();
DateTimeFormatter dtfEng = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
Locale.ENGLISH);
DateTimeFormatter dtfFr = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx uuuu",
Locale.FRENCH);
OffsetDateTime date1;
try {
date1 = OffsetDateTime.parse(dateq, dtfEng);
} catch (DateTimeParseException dtpe) {
// didn’t work in English, try French
date1 = OffsetDateTime.parse(dateq, dtfFr);
}
This handles both dim. janv. 23 24:00:00 +0000 2011
and Tue Feb 08 12:30:27 +0000 2011
.