SimpleDateFormat 问题 - 类型不匹配
SimpleDateFormat issue - type mismatch
我有将字符串值更改为日期的简单方法,但我一直收到错误消息。我已经导入 import java.sql.Date.
String lastDate = lastDate();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date datum = formatter.parse(lastDate); // type mismatch here
System.out.println(datum);
System.out.print(formatter.format(datum));
} catch (ParseException e){
e.printStackTrace();
}
我收到错误:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
如果我把 (Date) 放在 formatter.parse(lastDate) 前面;在我 运行 程序之前,我得到零错误。方法 lastDate 成功 returns 来自 SQL 数据库的最后日期,但随后出现以下错误。
Exception in thread "main" java.lang.NullPointerException
at java.text.SimpleDateFormat.parse(Unknown Source)
at java.text.DateFormat.parse(Unknown Source)
at meritve.prvi.main(prvi.java:108)
您将导入 java.sql.Date
和 SimpleDateFormat
的 parse 方法 returns java.util.Date
,因此您无法转换 formatter.parse(lastDate)
java.sql.Date
类型,所以 import java.util.Date
或者使用完整的 class 名称,如下所示:
I still get the bellow error: Exception in thread "main"
java.lang.NullPointerException
添加如下所示的null
检查,这样只有当lastDate
不为空时才会执行日期解析逻辑。
if(lastDate != null) {
java.util.Date datum = formatter.parse(lastDate);
System.out.println(datum);
System.out.print(formatter.format(datum));
}
我有将字符串值更改为日期的简单方法,但我一直收到错误消息。我已经导入 import java.sql.Date.
String lastDate = lastDate();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date datum = formatter.parse(lastDate); // type mismatch here
System.out.println(datum);
System.out.print(formatter.format(datum));
} catch (ParseException e){
e.printStackTrace();
}
我收到错误:
Type mismatch: cannot convert from java.util.Date to java.sql.Date
如果我把 (Date) 放在 formatter.parse(lastDate) 前面;在我 运行 程序之前,我得到零错误。方法 lastDate 成功 returns 来自 SQL 数据库的最后日期,但随后出现以下错误。
Exception in thread "main" java.lang.NullPointerException
at java.text.SimpleDateFormat.parse(Unknown Source)
at java.text.DateFormat.parse(Unknown Source)
at meritve.prvi.main(prvi.java:108)
您将导入 java.sql.Date
和 SimpleDateFormat
的 parse 方法 returns java.util.Date
,因此您无法转换 formatter.parse(lastDate)
java.sql.Date
类型,所以 import java.util.Date
或者使用完整的 class 名称,如下所示:
I still get the bellow error: Exception in thread "main" java.lang.NullPointerException
添加如下所示的null
检查,这样只有当lastDate
不为空时才会执行日期解析逻辑。
if(lastDate != null) {
java.util.Date datum = formatter.parse(lastDate);
System.out.println(datum);
System.out.print(formatter.format(datum));
}