2015-04-01 53 views
1

我无法通过从XML元素(我正在编写一个android应用程序)中解析字符串到日历对象,因此我可以计算字符串中的时间与当前时间之间的时间长度。我是全新的java来自.NET世界,所以在这里任何额外的背景可以真正有帮助。在Java中将字符串解析为日历?

我想使用的代码是:

// 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 = {[email protected]}"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 
+0

是什么'element.prdt'? – 2015-04-01 02:39:08

+0

对不起,应该指定 - 日历。我将编辑帖子。现在我意识到我可能必须以某种方式初始化它,因为它可能是一个引用类型? – tarun713 2015-04-01 02:40:01

+0

我猜datePRDT不会导致NPE,但'element'或'element.prdt'对象造成它。确保你初始化它们 – 2015-04-01 02:42:27

回答

1

两个问题与您的代码:

  • 解决您的SimpleDateFormat模式,只要您解析到位分钟mm个月MM的太!

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

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