I'm trying to print Date, just DateFormat.getDateTimeInstance()doing it.
Date
DateFormat.getDateTimeInstance()
formatgives a NullPointerExceptionwhen passing null, so I was wondering if there is another approach that will return null(or "null") instead?
format
NullPointerException
null
"null"
Something I would call instead
Date d = null; System.out.println(d==null ? null : DateFormat.getDateTimeInstance().format(d));
You can simply wrap the call inside the utility method:
public class DateUtils { public static String formatDateTime(Date dateOrNull) { return (dateOrNull == null ? null : DateFormat.getDateTimeInstance().format(dateOrNull)); } }
private constructor and javadoc are omitted for brevity.
What is the problem with your existing code?
null - , , ( "null") ( NPE). , , , , , .
, if-else, , , , ( null):
if (d == null) { return "null"; // or whatever special case } else { return DateFormat.getDateTimeInstance().format(d); }
javadocs .