Converting t+# to Date Format Using JavaScript

Here is a useful utility javascript function that converts date in the format t+# or t-# where t is today’s date and # is the days preceding or following today’s date. Value is input in the value field which popluates the result field on blur.

<form name="ipform">
    REGEX VALUE&nbsp;&nbsp;<input type="text" name="regexValue"
        id="regexValue" onBlur="executeValidation()" />
REGEX
    RESULT&nbsp;&nbsp;<input type="text" name="regexResult"
        id="regexResult" />
</form>
<script>
    function executeValidation() {
        var val = document.forms[0].regexValue.value;
        if (val != "") {
            var regex = "^t$|^t[\\+\\-][\\d]+$";

            if (testRegex(val.toLowerCase(), regex)) {
                var d = new Date();
                if (val == 't' || val == 'T') {
                    val = formatDate(d);
                    document.forms[0].regexResult.value = val;
                } else if (val.indexOf("-") != -1) {
                    var dateParse = val.split("-");
                    if (dateParse.length == 2) {
                        d.setDate(d.getDate() - parseInt(dateParse[1]));
                        val = formatDate(d);
                        document.forms[0].regexResult.value = val;
                    }
                } else if (val.indexOf("+") != -1) {
                    var dateParse = val.split("+");
                    if (dateParse.length == 2) {
                        d.setDate(d.getDate() + parseInt(dateParse[1]));
                        val = formatDate(d);
                        document.forms[0].regexResult.value = val;
                    }
                }
            }
        }
    }
    function formatDate(date) {
        var dateString = "";
        if (date) {
            var d = date.getDate();
            var day = (d < 10) ? '0' + d : d;
            if (isNaN(parseInt(day))) {
                dateString = '00/00/0000';
                return dateString;
            }
            var m = date.getMonth() + 1;
            if (isNaN(parseInt(m))) {
                dateString = '00/00/0000';
                return dateString;
            }
            var month = (m < 10) ? '0' + m : m;
            if (isNaN(parseInt(month))) {
                dateString = '00/00/0000';
                return dateString;
            }
            var yy = date.getFullYear();
            if (isNaN(parseInt(yy))) {
                dateString = '00/00/0000';
                return dateString;
            }
            yy += '';

            switch (yy.length) {
            case 0:
                yy = '0000';
                break;
            case 1:
                yy = '000' + yy;
                break;
            case 2:
                yy = '00' + yy;
                break;
            case 3:
                yy = '0' + yy;
                break;
            }
            dateString = month + "/" + day + "/" + yy;
        }
        return dateString;
    }
    function testRegex(val, regExp) {
        var flag = false;
        var re = new RegExp(regExp);
        if (val != "" && val.length > 0 && val.match(re)) {
            flag = true;
        }
        return flag;
    }
</script>

Applying regex patterns – In java and javascript

Regex patterns are easier to write than to read. Analysing the following regex patterns might give a good idea of how to come up with meaningful regex patterns:


All alphabets

^[a-zA-Z]*$

All digit

^[0-9]*$

All alphabets+digits

^[0-9a-zA-Z]*$

Email format

^[_a-zA-Z0-9-]+(.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$

Integers or decimals rounded to last two digits

^[0-9]+[.]?[0-9]{0,2}$

should be alphabets+digits with enclosed space

^[0-9a-zA-Z]+[0-9a-zA-Z\\s]*$

Can consist of Characters,space,dash,dot,pound,slash,quote

^[0-9a-zA-Z\\s\\-.#\\/’]*$

Can consist space,dash,quote

^[0-9a-zA-Z\\s\\-‘]*$

Can have 5 or 9 digits or; 10 digits when dash is included

^(d{5}|d{9}|d{5}-d{4})$
for example ZIP

Format for phone (US)

^([(]{1}[0-9]{3}[)]{1}[.| |-]{0,1}|^[0-9]{3}[.|-| ]?)?[0-9]{3}(.|-| )?[0-9]{4}$

should have 9 Digits and can have one dash
for instance TAXID

^[0-9]{9}$ (method to validate this in java below)

Should have 9 Digits

^[0-9]{9}$
For example SSN

private static boolean checkTAXID(String val) {
        boolean flag = false;
        String[] t = val.split("-");
        if (t.length < 2) {
            if (checkRegExp(val, "^[0-9]{9}$")) {
                flag = true;
            }
        }
        if (t.length == 2) {
            if ((val.length() == 10) && checkRegExp(t[0], "^[0-9]*$")
                    && checkRegExp(t[1], "^[0-9]*$")) {
                flag = true;
            }
        }
        if (t.length > 2) {
            flag = false;
        }
        return flag;
    }
 Below is a java method to validate the regular expresssions above:
	private static boolean checkRegExp(String val, String regExp) {
		 boolean flag = false;
		 if (null != val && !val.trim().equals("")) {
		 flag = val.matches(regExp);
		 }
		 return flag;
		 }

Here is a utility method to validate dates in various formats using regular expressions to recognize patterns and the SimpleDateFormat class to validate further:

public static final String returnedDateFormatString = "MM/dd/yyyy";

public static String validateDate(String paramDate) {
    DateFormat returnedDateFormat = new SimpleDateFormat(
            returnedDateFormatString);
    String regExp1 = "^[0-1]\\d[0-3]\\d[1-2]\\d{3}$";
    // -- matches MMDDYYYY
    String regExp2 = "^[0-1]*\\d[/.][0-3]*\\d[/.][1-2][\\d]{3}$";// --
    // matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
    String regExp3 = "^[0-1]*\\d[/.][0-3]*\\d[/.][\\d]{2}$";
    // (matches MM/DD/YY)(with or without leading zeroes for MM and DD)
    String regExp4 = "^[1-2][\\d]{3}[/.][0-1]*\\d[/.][0-3]*\\d$";
    // matches YYYY/MM/DD (with or without/ leading zeroes for MM and DD)
    String regExp5 = "^t$";// -- matches t
    String regExp6 = "^t[\\+\\-][\\d]+$";// -- matches t-# and t+#
    DateFormat dateFormat = null;
    Date date = null;
    if (checkRegExp(paramDate, regExp1)) {
        dateFormat = new SimpleDateFormat("MMddyyyy");
        try {
            date = dateFormat.parse(paramDate);
            if (dateFormat.format(date).equals(paramDate)) {
                return returnedDateFormat.format(date);
            }
        } catch (ParseException e) {
            date = null;
        }

    } else if (checkRegExp(paramDate, regExp2)) {
        String dateFormatArray[] = { "MM/dd/yyyy", "MM/d/yyyy",
                "M/dd/yyyy", "M/d/yyyy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yyyy", "MM.d.yyyy",
                "M.dd.yyyy", "M.d.yyyy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp3)) {
        String dateFormatArray[] = { "MM/dd/yy", "MM/d/yy", "M/dd/yy",
                "M/d/yy" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "MM.dd.yy", "MM.d.yy", "M.dd.yy",
                "M.d.yy" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    } else if (checkRegExp(paramDate, regExp4)) {
        String dateFormatArray[] = { "yyyy/MM/dd", "yyyy/MM/d",
                "yyyy/M/dd", "yyyy/M/d" };
        Date dateArray[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArray.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArray[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArray[i] = date;
                }
            } catch (ParseException e) {
                dateArray[i] = null;
            }
        }
        for (int i = 0; i < dateArray.length; i++) {
            if (dateArray[i] != null) {
                return returnedDateFormat.format(dateArray[i]);
            }
        }
        String dateFormatArrayDot[] = { "yyyy.MM.dd", "yyyy.MM.d",
                "yyyy.M.dd", "yyyy.M.d" };
        Date dateArrayDot[] = { null, null, null, null };
        for (int i = 0; i < dateFormatArrayDot.length; i++) {
            dateFormat = new SimpleDateFormat(dateFormatArrayDot[i]);
            try {
                date = dateFormat.parse(paramDate);
                if (dateFormat.format(date).equals(paramDate)) {
                    dateArrayDot[i] = date;
                }
            } catch (ParseException e) {
                dateArrayDot[i] = null;
            }
        }
        for (int i = 0; i < dateArrayDot.length; i++) {
            if (dateArrayDot[i] != null) {
                return returnedDateFormat.format(dateArrayDot[i]);
            }
        }
        return null;
    }
    return null;
}

Corresponding javascript method to validate regex:

function executePattern(val, regex) {
            var flg = false;
            var re = new RegExp(regex);
            if (val.length > 0 && !val.match(re)) {
                flg = true;
            }
            return flg;
        }

Here are some explanations for a few regex patterns:

^[0-1]d[0-3]d[1-2]d{3}$|^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3}$|^[0-1]*d[/.][0-3]*d[/.][d]{2}$|^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d$|^t$|^t[+-][d]+$

break up to explaining the pieces
^[0-1]d[0-3]d[1-2]d{3}$ — matches MMDDYYYY
^[0-1]*d[/.][0-3]*d[/.][1-2][d]{3} — matches MM/DD/YYYY (with or without leading zeroes for MM and DD)
^[0-1]*d[/.][0-3]*d[/.][d]{2} — matches MM/DD/YY (with or without leading zeroes for MM and DD)
^[1-2][d]{3}[/.][0-1]*d[/.][0-3]*d — matches YYYY/MM/DD (with or without leading zeroes for MM and DD)
^t — matches t
^t[+-][d]+$ — matches t-# and t+#
http://regexpal.com/ is a good site to see how your regex patterns match input data.