首页 > 解决方案 > 我无法将此字符串转换为日期

问题描述

我想将“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

标签: javadatetimesimpledateformat

解决方案


似乎您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()));

推荐阅读