Java Year Format isPartialYear(String s, String yearFormat)

Here you can find the source of isPartialYear(String s, String yearFormat)

Description

Allow only 4 digits, no more, no less

License

LGPL

Parameter

Parameter Description
s a parameter
yearFormat a parameter

Declaration

public static boolean isPartialYear(String s, String yearFormat) 

Method Source Code

//package com.java2s;
/*// w  ww  . java 2  s. 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-2005 Akaza Research
 */

import java.text.SimpleDateFormat;

public class Main {
    /**
     * Allow only 4 digits, no more, no less
     * 
     * @param s
     * @param yearFormat
     * @return
     * 
     * @author ywang (Nov., 2008)
     */
    public static boolean isPartialYear(String s, String yearFormat) {
        int dn = 0;
        char[] cyear = s.toCharArray();
        for (char c : cyear) {
            if (!Character.isDigit(c)) {
                return false;
            }
            ++dn;
        }
        if (dn != 4) {
            return false;
        }
        String yearformat = parseDateFormat(yearFormat) + "-MM-dd";
        SimpleDateFormat sdf_y = new SimpleDateFormat(yearformat);
        sdf_y.setLenient(false);
        String sy = s + "-01-18";
        try {
            sdf_y.parse(sy);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * return dateFormat with lowercase "y" and "d"
     * 
     * @param dateFormat
     * @return
     */
    public static String parseDateFormat(String dateFormat) {
        String s = dateFormat;
        while (s.contains("Y")) {
            s = s.replace("Y", "y");
        }
        while (s.contains("D")) {
            s = s.replace("D", "d");
        }
        return s;
    }
}

Related

  1. getYYYYMMDDHH(Date date)
  2. getYYYYMMDDHHMISS()
  3. getYYYYMMDDHHMMSS()
  4. getYYYYMMDDHHMMSS(Date date)
  5. getYyyyMMddWithoutDate()
  6. isValidDateMMddyyyy(String theString)
  7. isYear(int y)
  8. isYear(String str, boolean nullCheck)
  9. isYearOnly(String input)