我收到错误java.text.ParseException:无法解析的日期为null

时间:2020-06-26 10:01:39

标签: java date calendar

我希望日期格式为yyyy-MM-dd。我的代码是:

       Calendar cal = Calendar.getInstance();
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd", Locale.ENGLISH);
              cal.setTime(sdf.parse(row.getCell(67).toString()));

单元格中的值是:06/02/2020 但是,我得到的错误是:

java.text.ParseException: Unparseable date: "null"
    at java.text.DateFormat.parse(Unknown Source) ~[na:1.8.0_251]

感谢您的帮助。...

但是,我希望日期格式为yyyy-MM-dd。

这是完整的代码:

if(row.getCell(67).equals("null"))
                  {

                      Calendar cal = Calendar.getInstance();
                      cal.set(Calendar.YEAR, 1988);
                      cal.set(Calendar.MONTH, Calendar.JUNE);
                      cal.set(Calendar.DAY_OF_MONTH, 1);
                      Date dateRepresentation = cal.getTime();
                      rfx.setRv_rc_date(dateRepresentation);
                  }
                  else
                  {

                      Calendar cal = Calendar.getInstance();
                      SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd", Locale.ENGLISH);
                      cal.setTime(sdf.parse(row.getCell(67).toString()));
                      System.out.println("******************************************************");
                      System.out.println(cal);
                      System.out.println("*******************************************************");

                     

                  }
                  

1 个答案:

答案 0 :(得分:0)

我收到此错误:java.text.ParseException:无法解析的日期:“ 2020年1月30日”

在Google中搜索此日期时,我发现它位于French语言环境中,而您使用的是Locale.ENGLISH

enter image description here

如下所示,使用Locale.FRENCH来消除错误

SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd", Locale.FRENCH);

演示:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class Main {
    public static void main(String[] args) throws ParseException {
        // Input format
        SimpleDateFormat inputFormat = new SimpleDateFormat("dd-MMM-yyyy", Locale.FRENCH);
        Date date = inputFormat.parse("30-janv.-2020");

        // Output format
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(outputFormat.format(date));
    }
}

输出:

2020-01-30

但是,我建议您停止使用过时的日期时间API,并切换到modern date-time API,如下所示:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.FRENCH);
        LocalDate date = LocalDate.parse("30-janv.-2020", formatter);
        System.out.println(date);
    }
}

输出:

2020-01-30

请注意,我没有为此输出定义任何格式化程序,因为LocalDate#toString已经以您要求的格式返回了一个字符串。