Java Year Format isValidDateMMddyyyy(String theString)

Here you can find the source of isValidDateMMddyyyy(String theString)

Description

is Valid Date M Mddyyyy

License

LGPL

Declaration

static public String isValidDateMMddyyyy(String theString) 

Method Source Code


//package com.java2s;
/* //from   w w  w  .  ja v  a2s  . c o m
 * OpenClinica is distributed under the
 * GNU Lesser General Public License (GNU LGPL).
 * For details see: http://www.openclinica.org/license
 *
 * Copyright 2003-2008 Akaza Research 
 */

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    final static String MMddyyyySlashes = "[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}";
    final static String MMddyyyyFORMATSlashes = "MM/dd/yyyy";

    static public String isValidDateMMddyyyy(String theString) {
        String dateFormat = MMddyyyyFORMATSlashes;
        String dateRegexp = MMddyyyySlashes;
        return ifValidDateFormatAsyyyyMMdd(theString, dateFormat, dateRegexp);
    }

    static public String ifValidDateFormatAsyyyyMMdd(String theString, String format, String dateRegexp) {

        if (!theString.matches(dateRegexp)) {
            return theString;
        }

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date testDate = null;

        // Tried to parse with the above format
        try {
            testDate = sdf.parse(theString);
        } catch (ParseException e) {
            return theString;
        }

        // dateformat.parse will accept any date as long as it's in the format
        // you defined, it simply rolls dates over, for example, december 32
        // becomes jan 1 and december 0 becomes november 30
        // This statement will make sure that once the string
        // has been checked for proper formatting that the date is still the
        // date that was entered, if it's not, we assume that the date is invalid

        if (!sdf.format(testDate).equals(theString)) {
            return theString;
        }

        // if we make it to here without getting an error it is assumed that
        // the date was a valid one and that it's in the proper format

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String theNewString = sdf2.format(testDate);
        return theNewString;
    }
}

Related

  1. getYYYYMMDDHHMISS()
  2. getYYYYMMDDHHMMSS()
  3. getYYYYMMDDHHMMSS(Date date)
  4. getYyyyMMddWithoutDate()
  5. isPartialYear(String s, String yearFormat)
  6. isYear(int y)
  7. isYear(String str, boolean nullCheck)
  8. isYearOnly(String input)
  9. isYYYY(String strDate)