Checks if the Date is valid to convert. - Java java.util

Java examples for java.util:Calendar Calculation

Description

Checks if the Date is valid to convert.

Demo Code

/**/*from   w ww  .jav a2s . c o m*/
 * The MIT License
 *
 * Copyright (C) 2007 Asterios Raptis
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
//package com.java2s;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main {
    public static void main(String[] argv) throws Exception {
        String date = "java2s.com";
        String format = "java2s.com";
        boolean lenient = true;
        System.out.println(isValidDate(date, format, lenient));
    }

    /**
     * Checks if the Date is valid to convert.
     *
     * @param date
     *            The Date as String
     * @param format
     *            The Format for the Date to parse
     * @param lenient
     *            Specify whether or not date/time interpretation is to be lenient.
     * @return True if the Date is valid otherwise false.
     */
    public static boolean isValidDate(final String date,
            final String format, final boolean lenient) {
        boolean isValid = true;
        if (date == null || format == null || format.length() <= 0) {
            return false;
        }
        final DateFormat df = new SimpleDateFormat(format);
        df.setLenient(lenient);
        try {
            df.parse(date);
        } catch (final ParseException e) {
            isValid = false;
        }
        return isValid;
    }
}

Related Tutorials