我无法通过从 XML 元素中提取字符串并将其解析为 java 中的日历对象(我正在编写一个 android 应用程序),因此我可以计算字符串中的时间与当前时间之间的时间长度.我是 Java 的新手,来自 .NET 世界,因此这里的任何其他背景知识都非常有用。
我尝试使用的代码是:
// 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
最佳答案
您的代码有两个问题:
修复您的
SimpleDateFormat
模式,因为您正在解析分钟mm
以代替月份MM
!new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.ENGLISH); ^
您很可能忘记初始化您的
Calendar
实例,因此得到一个 NPE。element.prdt = Calendar.getInstance(); element.prdt.setTime(datePRDT);
关于java - 在 Java 中将字符串解析为日历?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29381900/