我无法将此字符串转换为日期
I can't convert this String to Date
我想将 "Thu Jan 18 00:00:00 CET 2018" 转换为“2018-01-18”-> yyyy-mm-dd。
但我收到错误 -> java.text.ParseException:无法解析的日期:"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;
}
也许这就是我弃用 cell.getCellType()
和 Cell.CELL_TYPE_NUMERIC
的原因?
好像你的Locale
不是这个格式,试试Locale.US
,你需要用x
作为时区,试试:
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
或者您可以使用 ZonedDateTime
因为 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()));
如果不指定语言环境,JVM 将使用系统的默认语言环境。如果这也恰好是美国英语(或 January 的缩写是 "Jan" 的其他语言),那么结果将是相同的。
请查看此线程:https://coderanch.com/t/491599/java/SimpleDateFormat-locale
我想将 "Thu Jan 18 00:00:00 CET 2018" 转换为“2018-01-18”-> yyyy-mm-dd。
但我收到错误 -> java.text.ParseException:无法解析的日期:"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;
}
也许这就是我弃用 cell.getCellType()
和 Cell.CELL_TYPE_NUMERIC
的原因?
好像你的Locale
不是这个格式,试试Locale.US
,你需要用x
作为时区,试试:
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
或者您可以使用 ZonedDateTime
因为 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()));
如果不指定语言环境,JVM 将使用系统的默认语言环境。如果这也恰好是美国英语(或 January 的缩写是 "Jan" 的其他语言),那么结果将是相同的。 请查看此线程:https://coderanch.com/t/491599/java/SimpleDateFormat-locale