Format the date, allowing

I'm trying to print Date, just DateFormat.getDateTimeInstance()doing it.

formatgives a NullPointerExceptionwhen passing null, so I was wondering if there is another approach that will return null(or "null") instead?

Something I would call instead

Date d = null;
System.out.println(d==null ? null : DateFormat.getDateTimeInstance().format(d));
+5
source share
2 answers

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.

+14
source

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 .

+2

All Articles