1

I need to convert String (in date format) to TimeStamp.

IN first I did like this.

private Timestamp dateConverter(String date) {
    Timestamp timestamp = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm");
    Date parsedDate = null;
    try {
        parsedDate = dateFormat.parse(date);
        timestamp = new java.sql.Timestamp(parsedDate.getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return timestamp;
}

Result was: ParseException: Unparseable date: "16 Jan 2020 11:02"

I tried by another way :

private Timestamp dateConverter(String date) {
    DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm");
    LocalDateTime ldt = LocalDateTime.parse(date , f);

    return Timestamp.valueOf(ldt);
}

At this time I have Internal Server Error with DateTimeParseException: Text '16 Jan 2020 11:02' could not be parsed at index 3

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • I recommend you don’t use `SimpleDateFormat`, `Date` and `Timestamp`. Those classes are poorly designed and long outdated, the first in particular notoriously troublesome. Instead use `LocalDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/), as in your second snippet. – Ole V.V. Jan 03 '20 at 22:57

1 Answers1

5

Your pattern can't know what is the language of your month, English, French, Arabic, Russian, Mandarin..., to solve this you have to help the formatter by using Locale like so :

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd MMM yyyy HH:mm")
                .withLocale(new Locale("us")); 
LocalDateTime ldt = LocalDateTime.parse("16 Jan 2020 11:02" , f); // 2020-01-16T11:02
Mohit Dodhia
  • 333
  • 4
  • 15
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140