问题描述
所以我得到一个来自传入对象的日期属性,形式如下:
So I get a date attribute from an incoming object in the form:
Tue May 24 05:05:16 EDT 2011
我写一个简单的帮助方法将其转换为日历方法,代码:
I am writing a simple helper method to convert it to a calendar method, I was using the following code:
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;
}
要模拟传入对象,我只是在当前使用的代码:
To simulate the incoming object I am just assigning the values within the code currently using:
private Date m_lastActivityDate = new Date();
但是这是一个空指针,一旦方法到达:
However this is givin me a null pointer once the method reaches:
date = (Date)formatter.parse(date.toString());
推荐答案
以下是您的方法:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
你所做的一切都是错误的和不必要的。
Everything else you are doing is both wrong and unnecessary.
BTW,Java命名约定建议方法名以小写字母开头,因此应为: dateToCalendar
或 toCalendar
(如图所示)。
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar
or toCalendar
(as shown).
?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
用于将字符串转换为日期( parse()
)或日期到字符串( format()
)。您正在使用它来解析日期的字符串表示回到日期。这不可能是对的,可以吗?
DateFormat
is used to convert Strings to Dates (parse()
) or Dates to Strings (format()
). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
这篇关于将Date对象转换为日历对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!