所以我从表单中的传入对象中获取日期属性:
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());
最佳答案
这是你的方法:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
你所做的一切都是错误和不必要的。
顺便说一句,Java 命名约定建议方法名称以小写字母开头,因此应该是:dateToCalendar
或 toCalendar
(如图所示)。
好的,让我们挤一下你的代码,好吗?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
用于将字符串转换为日期(parse()
)或将日期转换为字符串(format()
)。您正在使用它将日期的字符串表示解析回日期。这不可能吧?
关于java - 将 Date 对象转换为日历对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6185966/