問題描述
所以我從表單中的傳入對象中獲取日期屬性:
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.
順便說一句,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).
好的,讓我們擠一下你的代碼,好嗎?
OK, let's milk your code, shall we?
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 對象轉換為日歷對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!