Converting a Date object to a calendar object

JavaDateCalendarNullpointerexception

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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?

Solution 2 - Java

Just use Apache Commons

DateUtils.toCalendar(Date date)

Solution 3 - Java

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWillView Question on Stackoverflow
Solution 1 - JavaSean Patrick FloydView Answer on Stackoverflow
Solution 2 - JavaDavid TrujilloView Answer on Stackoverflow
Solution 3 - JavajsinaView Answer on Stackoverflow