dd-MMM-yyyy格式的java.time.format.DateTimeParseException [英] java.time.format.DateTimeParseException for dd-MMM-yyyy format

查看:124
本文介绍了dd-MMM-yyyy格式的java.time.format.DateTimeParseException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解析dd-MMM-yyyy格式的日期.

I am trying to parse date of dd-MMM-yyyy format.

package com.company;

import javax.swing.text.DateFormatter;
import java.time.format.DateTimeFormatter;

import java.time.*;
import java.util.Locale;

public class Main {

    public static void main(String[] args) {
        // write your code here
        MonthDay m;
        Locale.setDefault(Locale.ENGLISH);
        DateTimeFormatter dTF = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
        String dateString = "12-jan-1900";

        try
        {
            LocalDate ddd = LocalDate.parse(dateString,dTF);
            System.out.println(ddd.toString());
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //System.out.println(d.toString());

    }
}

它引发以下异常

java.time.format.DateTimeParseException: Text '12-jan-1900' could not be parsed at index 3
    at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    at java.time.LocalDate.parse(LocalDate.java:400)
    at com.company.Main.main(Main.java:20)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

它对于dd-MM-yyyy格式解析得很好,但是对于dd-MMM-yyyy格式却失败.我也很累设置Locale.US,但是在这种情况下也失败了.

It parses fine for dd-MM-yyyy format but fails with dd-MMM-yyyy format. I tired setting Locale.US also, but it failed in that case too.

推荐答案

原因是默认情况下解析是区分大小写的,并且格式化程序无法识别"jan".它只会识别"Jan".

The reason is that parsing is case sensitive by default and the formatter doesn't recognize "jan". It would only recognize "Jan".

您可以使用 DateTimeFormatterBuilder 并调用 parseCaseInsensitive() :

You can construct a case-insensitive parser by using a DateTimeFormatterBuilder and calling parseCaseInsensitive():

将格式样式的其余部分的解析样式更改为不区分大小写.

Changes the parse style to be case insensitive for the remainder of the formatter.

解析可以区分大小写或不区分大小写-默认情况下,区分大小写.此方法允许更改区分大小写的解析设置.

Parsing can be case sensitive or insensitive - by default it is case sensitive. This method allows the case sensitivity setting of parsing to be changed.

DateTimeFormatter dTF = 
    new DateTimeFormatterBuilder().parseCaseInsensitive()
                                  .appendPattern("dd-MMM-yyyy")
                                  .toFormatter();

这篇关于dd-MMM-yyyy格式的java.time.format.DateTimeParseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆