0

I want convert "Thu Jan 18 00:00:00 CET 2018" to "2018-01-18" -> yyyy-mm-dd.

But I get error -> java.text.ParseException: Unparseable date: "Thu Jan 18 00:00:00 CET 2018".

switch (cell.getCellType()) {
    case Cell.CELL_TYPE_NUMERIC:

    stringValue =  String.valueOf(cell.getDateCellValue());
    DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    Date date = (Date)formatter.parse(stringValue);
    System.out.println(date);        
   break;
   case Cell.CELL_TYPE_STRING:... 
   break;
}

Maybe is why I have cell.getCellType() and Cell.CELL_TYPE_NUMERIC deprecated ?

xingbin
  • 27,410
  • 9
  • 53
  • 103
EduBw
  • 866
  • 5
  • 20
  • 40
  • 1
    Side note: "Jan 18 2018" won't result in "2018-01-01" :) – Thomas Oct 01 '18 at 15:00
  • 2018-01-18 XDDD – EduBw Oct 01 '18 at 15:01
  • You’re overcomplicating it. Assuming you are uing Apache POI, `cell.getDateCellValue()` is already returning you a `java.util.Date`. Then your code converts that into a `String` and tries to convert it back into a `Date`. No reason to do that. – Ole V.V. Oct 02 '18 at 03:24
  • The `Date` class is not only long outdated, it also has a range of design problems with it. While I don’t think there’s a POI version that can give you something better, I suggest you do `Instant inst = cell.getDateCellValue().toInstant();` and use [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) from that point. – Ole V.V. Oct 02 '18 at 03:28

2 Answers2

1

Seems your Locale is not in this format, try Locale.US, and you need use x for timezone, try:

String input = "Thu Jan 18 00:00:00 CET 2018";

DateFormat parser = new SimpleDateFormat("E MMM dd HH:mm:ss x yyyy", Locale.US);
Date date = parser.parse(input); // parse String to Date

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(formatter.format(date)); // format Date to String

Or you can use ZonedDateTime since java8:

String input = "Thu Jan 18 00:00:00 CET 2018";

ZonedDateTime zonedDateTime = ZonedDateTime.parse(input,
        DateTimeFormatter.ofPattern("E MMM dd HH:mm:ss z yyyy", Locale.US));

System.out.println(DateTimeFormatter.ISO_DATE.format(zonedDateTime.toLocalDate()));
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

If you don't specify a locale, then JVM will use the default locale of the system. If that also happens to be US English (or some other language where the abbreviation for January is "Jan"), then the results will be the same. Please take a look at this thread : https://coderanch.com/t/491599/java/SimpleDateFormat-locale

RAGESH R
  • 11
  • 1