Converting a Date object to a calendar object

Will picture Will · May 31, 2011 · Viewed 339.2k times · Source

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()); 

Answer

Sean Patrick Floyd picture Sean Patrick Floyd · May 31, 2011

Here's your method:

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 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 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?