将日期对象转换为日历对象
因此,我从表单中的传入对象获取日期属性:
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());
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());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是你的方法:
你所做的其他一切都是错误的,也是不必要的。
顺便说一句,Java 命名约定建议方法名称以小写字母开头,因此应该是:
dateToCalendar
或toCalendar
(如图所示)。好吧,让我们榨取你的代码,好吗?
DateFormat
用于将字符串转换为日期 (parse()
) 或将日期转换为字符串 (format()
)。您正在使用它来将日期的字符串表示形式解析回日期。这不对吧?Here's your method:
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be:
dateToCalendar
ortoCalendar
(as shown).OK, let's milk your code, shall we?
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?只需使用 Apache Commons
DateUtils.toCalendar(日期日期)
Just use Apache Commons
DateUtils.toCalendar(Date date)
太简单了...将日期转换为日历,如下所示:
it's so easy...converting a date to calendar like this: