将字符串解析为 Java 中的日历?

Parsing String to Calendar in Java?

我无法通过从 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

您的代码有两个问题:

  • 在解析分钟 mm 代替月份 MM 时修正你的 SimpleDateFormat 模式!

    new SimpleDateFormat("yyyyMMdd HH:mm:ss", Locale.ENGLISH);
                              ^
    
  • 您很可能忘记初始化您的 Calendar 实例并因此获得 NPE。

    element.prdt = Calendar.getInstance();
    element.prdt.setTime(datePRDT);