格式化日期,允许为null [英] Format a Date, allowing null
本文介绍了格式化日期,允许为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印日期
,只是方式 DateFormat.getDateTimeInstance()
。
格式
在传递时抛出一个
,所以我一直在想,是否有不同的方法会返回 NullPointerException
null
(或null
)?
我会调用的东西不是
Date d = null;
System.out.println(d == null?null:DateFormat.getDateTimeInstance()。format(d));
解决方案
您可以在实用程序方法中包装调用:
public class DateUtils {
public static String formatDateTime(Date dateOrNull){
return(dateOrNull == null?null:DateFormat.getDateTimeInstance()。format(dateOrNull));
}
}
私有构造函数和javadoc为简洁省略。 >
I'm trying to print a Date
, just the way DateFormat.getDateTimeInstance()
does it.
format
throws a NullPointerException
when passing null
, so I've been wondering if there is a different approach that would return null
(or "null"
) instead?
Something I'd call instead of
Date d = null;
System.out.println(d==null ? null : DateFormat.getDateTimeInstance().format(d));
解决方案
You could just wrap the call inside a utility method :
public class DateUtils {
public static String formatDateTime(Date dateOrNull) {
return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull));
}
}
private constructor and javadoc omitted for brevity.
这篇关于格式化日期,允许为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文