Reputation: 2187
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
Upvotes: 1
Views: 336
Reputation: 51711
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);
Upvotes: 1