java.text.ParseException: Unparseable date: java.text.DateFo



我的SimpleDateFormat有问题。

SimpleDateFormat dtfmt=new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.getDefault());
Date dt=dtfmt.parse(deptdt);

在Android模拟器工作正常,但在手机我有这个错误:

W/系统。错误:java.text.ParseException: Unparseable date: "24 Oct 2016 7:31 pm"(偏移量3)W/系统。err: at java.text.DateFormat.parse(DateFormat.java:579)

解决方案吗?

永远不要在自定义格式中使用DateTimeFormatter,并且SimpleDateFormat没有Locale

由于给定的日期时间是英文的,您应该使用Locale.ENGLISH与您的日期时间解析器;否则,解析将在使用非英语语言环境类型的系统(计算机、电话等)中失败。

另外,请注意java.util的日期时间API和它们的格式化API SimpleDateFormat已经过时并且容易出错。建议完全停止使用它们并切换到现代日期时间API。

  • 无论出于何种原因,如果您必须坚持Java 6或Java 7,您可以使用ThreeTen-Backport,它支持大多数 Java。time功能到Java 6 &7 .
  • 如果你在一个Android项目上工作,你的Android API级别仍然不符合Java-8,检查Java 8+ API可通过糖和如何在Android项目中使用ThreeTenABP。
演示:

public class Main {
    public static void main(String[] args) {
        final String strDateTime = "24 Oct 2016 7:31 pm";
        DateTimeFormatter dtf = new DateTimeFormatterBuilder()
                .parseCaseInsensitive()             // For case-insensitive (e.g. am, Am, AM) parsing 
                .appendPattern("d MMM uuuu h:m a")  // Pattern conforming to the date-time string
                .toFormatter(Locale.ENGLISH);       // Locale
        LocalDateTime ldt = LocalDateTime.parse(strDateTime, dtf);
        System.out.println(ldt);
    }
}
输出:

2016-10-24T19:31
<<p> 在线演示/kbd>

默认情况下,DateTimeFormatter#ofPattern使用JVM在启动时根据主机环境设置的默认FORMAT区域设置。SimpleDateFormat的情况也是如此。我试图通过下面的演示来说明这个问题:

public class Main {
    public static void main(String[] args) {
        final String strDateTime = "24 Oct 2016 7:31 pm";           
        DateTimeFormatter dtfWithDefaultLocale = null;          
        System.out.println("JVM's Locale: " + Locale.getDefault());
        // Using DateTimeFormatter with the default Locale
        dtfWithDefaultLocale = getDateTimeFormatterWithDefaultLocale();
        System.out.println("DateTimeFormatter's Locale: " + dtfWithDefaultLocale.getLocale());
        System.out.println(
                "Parsed with JVM's default locale: " + LocalDateTime.parse(strDateTime, dtfWithDefaultLocale));
        // Setting the JVM's default locale to Locale.FRANCE
        Locale.setDefault(Locale.FRANCE);
        
        // Using DateTimeFormatter with Locale.ENGLISH explicitly (recommended)
        DateTimeFormatter dtfWithEnglishLocale = getDateTimeFormatterWithEnglishLocale();
        System.out.println("JVM's Locale: " + Locale.getDefault());
        System.out.println("DateTimeFormatter's Locale: " + dtfWithEnglishLocale.getLocale());
        LocalDateTime zdt = LocalDateTime.parse(strDateTime, dtfWithEnglishLocale);
        System.out.println("Parsed with Locale.ENGLISH: " + zdt);
        
        System.out.println("JVM's Locale: " + Locale.getDefault());
        // Using DateTimeFormatter with the default Locale
        dtfWithDefaultLocale = getDateTimeFormatterWithDefaultLocale();
        System.out.println("DateTimeFormatter's Locale: " + dtfWithDefaultLocale.getLocale());
        System.out.println(
                "Parsed with JVM's default locale: " + LocalDateTime.parse(strDateTime, dtfWithDefaultLocale));
    }
    
    static DateTimeFormatter getDateTimeFormatterWithDefaultLocale() {
        return new DateTimeFormatterBuilder()
                .parseCaseInsensitive()             
                .appendPattern("d MMM uuuu h:m a") 
                .toFormatter(); // Using default Locale
    }
    
    static DateTimeFormatter getDateTimeFormatterWithEnglishLocale() {
        return new DateTimeFormatterBuilder()
                .parseCaseInsensitive()             
                .appendPattern("d MMM uuuu h:m a") 
                .toFormatter(Locale.ENGLISH); // Using Locale.ENGLISH
    }
}
输出:

JVM's Locale: en_GB
DateTimeFormatter's Locale: en_GB
Parsed with JVM's default locale: 2016-10-24T19:31
JVM's Locale: fr_FR
DateTimeFormatter's Locale: en
Parsed with Locale.ENGLISH: 2016-10-24T19:31
JVM's Locale: fr_FR
DateTimeFormatter's Locale: fr_FR
Exception in thread "main" java.time.format.DateTimeParseException: Text '24 Oct 2016 7:31 pm' could not be parsed at index 3
    at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
    at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
    at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at Main.main(Main.java:34)
<<p> 在线演示/kbd>

为了完整起见,下面的演示使用SimpleDateFormat:

public class Main {
    public static void main(String[] args) throws ParseException {
        final String strDateTime = "24 Oct 2016 7:31 pm";
        SimpleDateFormat sdf = new SimpleDateFormat("d MMM yyyy h:m a", Locale.ENGLISH);
        Date date = sdf.parse(strDateTime);
        System.out.println(date);
    }
}
输出:

Mon Oct 24 19:31:00 BST 2016
<<p> 在线演示/kbd>

您的deptdt包含Oct,看起来像英文月份名称。但是您的Locale.getDefault()可能给出一个非英语区域设置。替换为Locale.ENGLISHLocale.US:

SimpleDateFormat dtfmt=new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH);
Date dt=dtfmt.parse(deptdt);

这可能是因为手机的默认语言环境不是英语,而您输入的月份名称是(Oct)。

解决方案是显式使用英语区域设置:

SimpleDateFormat dtfmt = new SimpleDateFormat("dd MMM yyyy hh:mm a", Locale.ENGLISH);
Date dt = dtfmt.parse("24 Oct 2016 7:31 pm");

不用直接使用SimpleDateFormat(因为这个旧API有很多问题和设计问题),你可以使用ThreeTen Backport,这是Java 8新日期/时间类的一个很好的后端口。要在Android中使用它,你还需要ThreeTenABP(更多关于如何使用它在这里)。

要使用的主要类是org.threeten.bp.LocalDateTime(这似乎是最好的选择,因为您的输入中有日期和时间字段)和org.threeten.bp.format.DateTimeFormatter(用于解析输入)。我还使用java.util.Locale类来确保它解析英文月份名称,并使用org.threeten.bp.format.DateTimeFormatterBuilder来确保它解析pm(使其不区分大小写,因为默认是PM):
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
    // case insensitive to parse "pm"
    .parseCaseInsensitive()
    // pattern
    .appendPattern("dd MMM yyyy h:mm a")
    // use English locale to parse month name (Oct)
    .toFormatter(Locale.ENGLISH);
// parse input
LocalDateTime dt = LocalDateTime.parse("24 Oct 2016 7:31 pm", fmt);
System.out.println(dt); // 2016-10-24T19:31

输出将是:

2016 - 10 - 24 t19:31

如果您需要将其转换为java.util.Date,则可以使用org.threeten.bp.DateTimeUtils类。但是您还需要知道将使用哪个时区来转换它。在下面的例子中,我使用"UTC":

Date date = DateTimeUtils.toDate(dt.atZone(ZoneOffset.UTC).toInstant());

要切换到不同的区域,可以这样做:

Date date = DateTimeUtils.toDate(dt.atZone(ZoneId.of("Europe/London")).toInstant());

请注意API使用IANA时区名称(总是以Continent/City的格式,如America/Sao_PauloEurope/Berlin)。避免使用3个字母的缩写(如CSTPST),因为它们含糊不清且不标准。要找到更适合每个地区的时区,请使用ZoneId.getAvailableZoneIds()方法并检查哪个最适合您的用例。

PS:上面最后一个示例(dt.atZone(ZoneId.of("Europe/London")))将在伦敦时区创建日期/时间2016-10-24T19:31。但是如果你想要的是UTC的2016-10-24T19:31,然后将其转换为另一个时区,那么你应该这样做:

Date date = DateTimeUtils.toDate(dt
    // first convert it to UTC
    .toInstant(ZoneOffset.UTC)
    // then convert to LondonTimezone
    .atZone(ZoneId.of("Europe/London")).toInstant());

最新更新