1

I am having trouble parsing a string to a calendar object in java by pulling it from an XML element (I'm writing an android app) so I can calculate the length of time between the time in the string and the current time. I am brand new to java and come from the .NET world, so any additional background here can be really helpful.

The code I am trying to use is:

// Using this class to define the format for date parsing.
SimpleDateFormat sdf = new SimpleDateFormat("yyyymmdd HH:mm:ss", Locale.ENGLISH);

// readArrivalValue reads the element from XML, which seems to be working.
String prdt = readArrivalValue(parser, "prdt");
// At this point prdt evaluates to the correct value: "20150331 20:14:40"

Date datePRDT = sdf.parse(prdt);
// datePRDT doesn't seem to be set properly. It evaluates to:
//    datePRDT = {java.util.Date@830031077456}"Sat Jan 31 20:14:40 CST 2015"
//      milliseconds = 1422761216000

// element.prdt is of type Calendar. Nothing is done to this prior to this statement.
element.prdt.setTime(datePRDT); // This throws a null pointer exception
7
  • what is element.prdt? Commented Apr 1, 2015 at 2:39
  • Sorry, should have specified that - Calendar. I'll edit the post. And now I'm realizing I probably have to initialize that in some way, as it might be a reference type? Commented Apr 1, 2015 at 2:40
  • I am guessing that datePRDT is not causing the NPE but either element or element.prdt object is causing it. Make sure you initialized them Commented Apr 1, 2015 at 2:42
  • That makes sense, as it's not initialized. Is it best practice to use Calendar.getInstance() in this case to initialize, or just new GregorianCalendar() ? And why is my parse coming back with the wrong value? Commented Apr 1, 2015 at 2:45
  • I would recommend using the getInstance that it will directly use the date of the system where you are running it. Commented Apr 1, 2015 at 2:46

1 Answer 1

1

Two issues with your code:

  • Fix your SimpleDateFormat pattern as you're parsing minutes mm in place of months MM too!

    new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.ENGLISH);
                              ^
    
  • You most likely forgot to initialize your Calendar instance and hence get an NPE.

    element.prdt = Calendar.getInstance();
    element.prdt.setTime(datePRDT);
    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.