Returns the specified date or the epoch date if the provided one was null. - Java java.util

Java examples for java.util:Date Compare

Description

Returns the specified date or the epoch date if the provided one was null.

Demo Code


//package com.java2s;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        Date date = new Date();
        System.out.println(nullSafe(date));
    }//from   w w w .  j  ava 2  s.  c o m

    /**
     * Returns the specified date or the epoch date if the provided one was null.
     *
     * @param date
     *            the date to return
     * @return the specified date or the epoch date if the provided one was null.
     */
    @Deprecated
    public static Date nullSafe(Date date) {
        Date result = date;
        if (result == null) {
            result = new Date(0);
        }

        return result;
    }

    /**
     * Returns the specified calendar or the epoch date if the provided one was null.
     *
     * @param calendar
     *            the calendar to return
     * @return the specified calendar or the epoch date if the provided one was null.
     */
    public static Calendar nullSafe(Calendar calendar) {
        return nullSafe(calendar, new GregorianCalendar(1970, 0, 1));
    }

    /**
     * Returns the specified calendar or - if it's null - a specified fallback value.
     *
     * @param defaultValue
     *            the default calendar to return
     * @param fallbackValue
     *            the value to return when the default is null
     * @return the specified calendar or - if it's null - a fallback value.
     */
    public static Calendar nullSafe(Calendar defaultValue,
            Calendar fallbackValue) {
        return defaultValue != null ? defaultValue : fallbackValue;
    }
}

Related Tutorials