java.text.ParseException:无法解析的日期:java.text.DateFormat.parse(DateFormat.java:579)

问题描述 投票:0回答:3

我有问题

SimpleDateFormat

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

在 Android 模拟器中工作正常,但在手机中出现此错误:

W/System.err:java.text.ParseException:无法解析的日期:“2016 年 10 月 24 日下午 7:31”(偏移量 3) W/System.err:位于 java.text.DateFormat.parse(DateFormat.java:579)

有什么解决办法吗?

java android date datetime-parsing unparseable
3个回答
6
投票

切勿将
DateTimeFormatter
用于自定义格式,并且
SimpleDateFormat
不使用
Locale

由于给定的日期时间是英文的,因此您应该将

Locale.ENGLISH
与日期时间解析器一起使用;否则,在使用非英语类型语言环境的系统(计算机、电话等)中解析将会失败。

另请注意,

java.util
的日期时间 API 及其格式化 API
SimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API

演示:

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

在线演示

默认情况下,

DateTimeFormatter#ofPattern
使用 JVM 在启动期间根据主机环境设置的默认格式区域设置
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)

在线演示


以下演示使用

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

在线演示


2
投票

您的

deptdt
包含
Oct
,看起来像英文月份名称。 但是您的
Locale.getDefault()
可能会提供非英语区域设置。 将其替换为
Locale.ENGLISH
Locale.US
:

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

2
投票

发生这种情况可能是因为手机的默认语言环境不是英语,而您输入的月份名称是(

Oct
)。

解决方案是明确使用英语语言环境:

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

您可以使用

ThreeTen Backport
,而不是直接使用 SimpleDateFormat(因为这个旧 API 有 很多问题设计问题),它是 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-24T19: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_Paulo
Europe/Berlin
)。 避免使用 3 个字母的缩写(如
CST
PST
),因为它们不明确且不标准。要找到更适合每个地区的时区,请使用
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());
© www.soinside.com 2019 - 2024. All rights reserved.