I´m trying to convert a String date like "Thu May 24 2018 14:00:00 GMT+0200" to Joda DateTime (v.2.9.9) but I obtain Invalid format exception:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
for (int i=0; i < arrayHorarios.length; i++) {
DateTime dateTime = new DateTime();
dateTime = formatter.withOffsetParsed().parseDateTime(arrayHorarios[i]);
}
What am I doing wrong? My goal is to convert all Strings containing dates to Java Dates and then save them into DB... what´s the easiest way to do it? (with or without Joda).
EDIT:
I changed to the correct pattern. Using Java DateFormat was useless too:
ObjectMapper mapper = new ObjectMapper();
String[] arrayHorarios = mapper.readValue(horariosSave, String[].class);
DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
List<Date> hor = new ArrayList<Date>();
Date date = new Date();
try {
for (int i=0; i < arrayHorarios.length; i++) {
// conversión de String a Date de los valores
System.out.println("Horario nº:"+i);
System.out.println("String = "+arrayHorarios[i]);
date = df.parse(arrayHorarios[i]);
System.out.println("Date = " + df.format(date));
hor.add(date);
}
System.out.println("Clases guardadas:"+hor.size());
} catch (Exception e) {
e.printStackTrace();
}
This way I get this exception:
java.text.ParseException: Unparseable date: "Fri May 25 2018 12:00:00 GMT+0200" at java.text.DateFormat.parse(DateFormat.java:366)
I wonder if there is a way to do it with Java 8 Util Time.
Of course there is.
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
OffsetDateTime dateTime = OffsetDateTime.parse(horario, formatter);
System.out.println(dateTime);
Prints:
2018-05-24T14:00+02:00
Imports used are:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
Not that you’ll regret upgrading to java.time
, your Joda-Time code seems to be working too:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(horario);
System.out.println(dateTime);
This prints:
2018-05-24T14:00:00.000+02:00
I suspect that your problem may be somewhere else.
PS You may already be aware that the Joda-Time home page says:
Users are now asked to migrate to
java.time
(JSR-310).