错误:尝试解析字符串日期时无法在索引0处解析文本“ 1/31/2020” [英] Error: Text '1/31/2020' could not be parsed at index 0 while trying to parse string date

查看:734
本文介绍了错误:尝试解析字符串日期时无法在索引0处解析文本“ 1/31/2020”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期作为字符串,如下所示

 字符串测试日期= 1/31/2020; 

我正在使用以下代码

 公共静态字符串getPeriodMonth(String periodEndDate){
LocalDate localDate;
YearMonth yearMonth = null;
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( MM / dd / yyyy);
localDate = LocalDate.parse(periodEndDate,formatter);
yearMonth = YearMonth.from(localDate);
} catch(异常e){
LOGGER.error(错误: + e.getMessage()+>> + e.getCause());
}
return yearMonth.toString();

}

执行此代码时,我得到以下异常:

 错误:无法在索引0>> null 

有人可以帮我在这里做错什么吗?

解决方案

您应该通过 01/31/2020 或将格式更新为 M / dd / yyyy


DateTimeFormatter文档


在文档中将月份视为一个数字:


数字:如果字母数为1,则该值使用最少的位数输出,不带填充。否则,将数字的计数用作输出字段的宽度,并在必要时将值补零。



I have a date as string as below

String test Date = "1/31/2020";

I am using the below code

public static String getPeriodMonth(String periodEndDate) {
        LocalDate localDate;
        YearMonth yearMonth = null;
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
            localDate = LocalDate.parse(periodEndDate, formatter);
            yearMonth = YearMonth.from(localDate);
        }catch (Exception e) {
             LOGGER.error("Error: "+ e.getMessage() + ">>" +   e.getCause());
        }
        return yearMonth.toString();

    }

I am getting the below Exception when excuting this code:

Error: Text '1/31/2020' could not be parsed at index 0>>null

Can someone help me what I am doing wrong here?

解决方案

You should pass 01/31/2020or update the format to M/dd/yyyy

DateTimeFormatter documentation

The month is considered as a number and in the documentation :

Number: If the count of letters is one, then the value is output using the minimum number of digits and without padding. Otherwise, the count of digits is used as the width of the output field, with the value zero-padded as necessary.

这篇关于错误:尝试解析字符串日期时无法在索引0处解析文本“ 1/31/2020”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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