Home  >  Article  >  Web Front-end  >  Two ways to determine the input date in JavaScript

Two ways to determine the input date in JavaScript

高洛峰
高洛峰Original
2016-11-25 11:02:091332browse

JavaScript code
/// Check whether the entered date is a correct date format:
/// Supports four input formats: yyyy-M-d, yyyy-MM-dd, yyyy/M/d, yyyy/MM/dd.

function checkDate(strInputDate) {
// Define a constant array of days in a month
var DA = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

// Unified date format
strDate = strInputDate.replace(/-/g, "/");

// Determine whether the date is in the expected format
if (strDate.indexOf("/") == -1) {
alert("Please enter the format of yyyy-M-d, yyyy-MM-dd, yyyy/M/d, yyyy/MM/dd.")
return false;
}

// Decompose the year, month and day
arrD = strDate.split("/");
if (arrD.length != 3) return false;
y = parseInt(arrD[0], 10);
m = parseInt(arrD[1], 10);
d = parseInt(arrD[2], 10);

//Judge whether the year, month and day are numbers
if (isNaN(y) || isNaN(m) || isNaN(d)) return false;

//Judge Whether the month is between 1-12
if (m > 12 || m < 1) return false;
//Determine whether it is a leap year
if (isLoopYear(y)) DA[2] = 29;

/ /Determine whether the entered day exceeds the total number of days in the current month.
if (d > DA[m]) return false;

//If all conditions are verified, it should be a legal date.
// If you want to format the date once, you can do it here. The following formats it into the date format recognized by the database yyyy-MM-dd
// str = y + "-" + (m<10?" 0":"") + m + "-" + (d<10?"0":"") + d;
str = y + "-" + (m < 10 ? "0" : "") + m + "-" + (d < 10 ? "0" : "") + d;
alert(str)
return true;
}
function isLoopYear(theYear) {
return (new Date(theYear, 1 , 29).getDate() == 29);
}

//Method 2:
/// Check whether the entered date is a correct date format:
/// Supports yyyy-M-d, yyyy-MM- There are four input formats: dd, yyyy/M/d, yyyy/MM/dd.
function CheckDate2(strInputDate) {
if (strInputDate == "") return false;
strInputDate = strInputDate.replace(/-/g, "/");
var d = new Date(strInputDate);
if (isNaN (d)) return false;
var arr = strInputDate.split("/");
return ((parseInt(arr[0], 10) == d.getFullYear()) && (parseInt(arr[1], 10) == (d.getMonth() + 1)) && (parseInt(arr[2], 10) == d.getDate()));
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn