Java SimpleDateFormat无法将给定的对象格式化为日期



我试图使用日期格式将字符串转换为日期,并使用了以下代码,但它显示了一个错误。

public static Date ConvertStringtodate(String Date) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date Teststart = dateFormat.parse(Date);
return Teststart;
}
public static void main(String[]agrs) throws ParseException {
System.out.println(ConvertStringtodate("2022.02.10 17:54:55"));
}

这是错误

线程中的异常"主";java.lang.IollegalArgumentException:无法将给定对象格式化为日期java.text.DateFormat.format(DateFormat.java:310(java.text.Format.Format(Format.java:157(

在main方法中,您将日期发送为"2022.02.10 17:54:55";。然而,您将模式的格式写为";yyyy-MM-dd hh:MM:ss";。将SimpleDateFormat构造函数处的模式更改为";yyyy。MM.dd HH:MM:ss";。

我的问题是日期输入中的斜杠'/'。出于某种原因。输入字符串是";1991年1月1日";而不是";1991年1月1日";。所以我只是用破折号代替了斜线,一切都很好。

private Date convertStringToDate(String payload) throws ParseException {
payload = payload.replace("/", "-");
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
java.util.Date utilDate = formatter.parse(payload);
return new Date(utilDate.getTime());
}

最新更新