【发布时间】:2011-09-05 08:53:54
【问题描述】:
所以我从表单中的传入对象中获取日期属性:
Tue May 24 05:05:16 EDT 2011
我正在编写一个简单的辅助方法来将其转换为日历方法,我使用的是以下代码:
public static Calendar DateToCalendar(Date date )
{
Calendar cal = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
cal=Calendar.getInstance();
cal.setTime(date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
return cal;
}
为了模拟传入的对象,我只是在当前使用的代码中分配值:
private Date m_lastActivityDate = new Date();
但是,一旦方法到达,这会给我一个空指针:
date = (Date)formatter.parse(date.toString());
【问题讨论】:
-
对于迟到的人:我建议您既不要使用
Date,也不要使用Calendar。这些课程设计不良且早已过时。而是使用来自java.time, the modern Java date and time API 的Instant和ZonedDateTime。
标签: java date calendar nullpointerexception