日期时间字符串验证器(typescript)

// 校验时间格式的字符串是否符合[yyyy-mm-dd hh24:mi:ss] 或者 [yyyy/mm/dd hh24:mi:ss]的格式, 可以精确到分钟
function validateDateStr(dateStr: string) {

    if (dateStr.length > 19) {
        return false;
    }

    let mpSec1 = /^\d{4}-(\d{2}|\d{1}|0\d{1})-([1-3]\d{1}|0\d{1}|\d{1})\ (2[0-3]|1\d{1}|0\d{1}|\d{1})\:([0-5]\d{1}):([0-5]\d{1})$/;
    let mpMin1 = /^\d{4}-(\d{2}|\d{1}|0\d{1})-([1-3]\d{1}|0\d{1}|\d{1})\ (2[0-3]|1\d{1}|0\d{1}|\d{1})\:([0-5]\d{1})$/;
    let mpSec2 = /^\d{4}\/(\d{2}|\d{1}|0\d{1})\/([1-3]\d{1}|0\d{1}|\d{1})\ (2[0-3]|1\d{1}|0\d{1}|\d{1})\:([0-5]\d{1}):([0-5]\d{1})$/;
    let mpMin2 = /^\d{4}\/(\d{2}|\d{1}|0\d{1})\/([1-3]\d{1}|0\d{1}|\d{1})\ (2[0-3]|1\d{1}|0\d{1}|\d{1})\:([0-5]\d{1})$/;

    let matchArray1 = dateStr.match(mpSec1) || dateStr.match(mpMin1);
    let matchArray2 = dateStr.match(mpSec2) || dateStr.match(mpMin2);

    if (matchArray1 == null && matchArray2 == null) {
        return false;
        //throw new InvalidArgumentException(metadata.data, dateStr, '请确认日期是否符合[yyyy-mm-dd hh24:mi:ss] 或者 [yyyy/mm/dd hh24:mi:ss]的格式!')
    }

    const arrayDate = dateStr.split(" ");
    const strDate = arrayDate[0];
    const strTime = arrayDate[1];

    let iaMonthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    let iaDate = new Array(3);
    let iaTime = new Array(3);
    let year: number, month: number, day: number, hour: number, minute: number, second: number;

    if (matchArray1) iaDate = strDate.split("-");
    else if (matchArray2) iaDate = strDate.split("/");

    iaTime = strTime.split(":");

    year = parseFloat(iaDate[0]);
    month = parseFloat(iaDate[1]);
    day = parseFloat(iaDate[2]);

    hour = parseFloat(iaTime[0]);
    minute = parseFloat(iaTime[1]);
    if (second)
        second = parseFloat(iaTime[2]);

    if (year < 1900 || year > 2999) {
        return false;
        //throw new InvalidArgumentException(metadata.data, dateStr, '请确认日期年限是否准确');
    }

    if (month < 1 || month > 12) {
        return false;
        // throw new InvalidArgumentException(metadata.data, dateStr, '请确认日期月份是否准确');
    }

    // 闰年2月的天数
    if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
        iaMonthDays[1] = 29;
    }

    if (day < 1 || day > iaMonthDays[month - 1]) {
        return false;
        // throw new InvalidArgumentException(metadata.data, dateStr, '请确认日期天是否准确');
    }

    if (hour > 23) {
        return false;
        // throw new InvalidArgumentException(metadata.data, dateStr, '请确认时间是否准确');
    }

    if (minute > 59) {
        return false;
        // throw new InvalidArgumentException(metadata.data, dateStr, '请确认分秒是否准确');
    }

    if (second && (second < 0 || second > 59))
        return false;

    return true;
}

点击数:44

发表评论

您的电子邮箱地址不会被公开。

*

code