Checks the String whether it is a valid date in format yyyy-MM-dd. - Java java.util

Java examples for java.util:Date Parse

Description

Checks the String whether it is a valid date in format yyyy-MM-dd.

Demo Code


//package com.java2s;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        String dateString = "java2s.com";
        System.out.println(validString(dateString));
    }/* ww w  .  jav  a 2s. c  o m*/

    /**
     * Default date format in the form 2013-03-18.
     */
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd");

    /**
     * Checks the String whether it is a valid date.
     * 
     * @param dateString
     * @return true if the String is a valid date
     */
    public static boolean validString(String dateString) {
        try {
            DATE_FORMAT.parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     * Converts a String in the format "yyyy-MM-dd" to a Calendar object.
     * 
     * Returns null if the String could not be converted.
     * 
     * @param dateString the date as String
     * @return the calendar object or null if it could not be converted
     */
    public static Calendar parse(String dateString) {
        Calendar result = Calendar.getInstance();
        try {
            result.setTime(DATE_FORMAT.parse(dateString));
            return result;
        } catch (ParseException e) {
            return null;
        }
    }
}

Related Tutorials