现在我知道什么是null NullPointerException 什么是NullPointerException,如何解决?但不明白为什么我要这样做。
我正在从这个问题中更改示例在android中更改日期字符串格式
我从服务器获取日期作为字符串。"2020-03-11T00:00:00",
基本上是用户续签合同的日期。
@SerializedName("renewalDate")
private String date;
在我的getter方法中,我正在这样做:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = new Date();
try {
newDate = format.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
format = new SimpleDateFormat("dd-MMM-yyyy");
return format.format(newDate); }
现在,我的String日期不是空的,因为日志从服务器正确显示了日期,这就是为什么我如此困惑为什么我得到NullPointerException的原因。
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at java.text.SimpleDateFormat.parseInternal(SimpleDateFormat.java:1739)
at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1726)
at java.text.DateFormat.parse(DateFormat.java:360)
at com.nswd.successplan.model.RealEsteteModel.getDate(RealEsteteModel.java:147)
at com.nswd.successplan.databinding.ItemRealEsteteAccBindingImpl.executeBindings(ItemRealEsteteAccBindingImpl.java:198)
at androidx.databinding.ViewDataBinding.executeBindingsInternal(ViewDataBinding.java:473)
at androidx.databinding.ViewDataBinding.executePendingBindings(ViewDataBinding.java:445)
at com.nswd.successplan.Adapters.RealEsteteAdapter$RealEsteteHolder.binding(RealEsteteAdapter.java:79)
at com.nswd.successplan.Adapters.RealEsteteAdapter.onBindViewHolder(RealEsteteAdapter.java:46)
at com.nswd.successplan.Adapters.RealEsteteAdapter.onBindViewHolder(RealEsteteAdapter.java:25)
对于日期时间字符串2020-03-11T00:00:00
,您需要替换
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
与
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
注意: java.util.Date
不代表日期/时间对象。它只是表示否。距纪元的毫秒数1970-01-01T00:00:00Z
。它没有任何时区或时区偏移信息。在打印时,Java将打印通过应用JVM的时区获得的字符串。我建议您从过时且容易出错的java.util
日期时间API SimpleDateFormat
切换到现代 java.time
日期时间API和相应的格式API(包java.time.format
)。从Trail:Date Time了解更多有关现代日期时间API的信息。如果您的Android API级别仍不符合Java8,请检查如何在Android Project中使用ThreeTenABP和可通过desugaring获得的Java 8+ API。
下表概述了现代日期时间类,您可以根据需要从中选择类:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句