我使用文本字段在我的表单中获取日期,我使用jquery编码进行日期验证(mm / dd / yyyy)。
function isDate(txtDate) {
var objDate, // date object initialized from the txtDate string
mSeconds, // txtDate in milliseconds
day, // day
month, // month
year; // year
// date length should be 10 characters (no more no less)
if (txtDate.length !== 10) {
return false;
}
// third and sixth character should be '/'
if (txtDate.substring(2, 3) !== '/' || txtDate.substring(5, 6) !== '/') {
return false;
}
// extract month, day and year from the txtDate (expected format is mm/dd/yyyy)
// subtraction will cast variables to integer implicitly (needed
// for !== comparing)
month = txtDate.substring(0, 2) - 1; // because months in JS start from 0
day = txtDate.substring(3, 5) - 0;
year = txtDate.substring(6, 10) - 0;
// test year range
if (year < 1000 || year > 3000) {
return false;
}
// convert txtDate to milliseconds
mSeconds = (new Date(year, month, day)).getTime();
// initialize Date() object from calculated milliseconds
objDate = new Date();
objDate.setTime(mSeconds);
// compare input date and parts from Date() object
// if difference exists then date isn't valid
if (objDate.getFullYear() !== year ||
objDate.getMonth() !== month ||
objDate.getDate() !== day) {
return false;
}
// otherwise return true
return true;
}
这适用于日期格式(mm / dd / yyyy)..但现在我需要支持像(m / d / yyyy)这样的格式。
我该怎么做?
答案 0 :(得分:0)
这些修改的示例将支持这两种格式:
// date length should be between 8 and 10 characters (no more no less)
if (txtDate.length < 8 || txtDate.length > 10) {
return false;
}
var tokens = txtDate.split('/');
// there should be exactly three tokens
if (tokens.length !== 3) {
return false;
}
// extract month, day and year from the txtDate
month = parseInt(tokens[0]) - 1; // because months in JS start from 0
day = parseInt(tokens[1]);
year = parseInt(tokens[2]);
答案 1 :(得分:0)
试用date.js库
这样你就可以编写如下代码:
Date.parse('7/1/2004') // Thu Jul 01 2004
Date.js中的所有解析都可以通过包含包含文化信息的文件进行全球化,因此您应该能够使其按照您的意愿进行。
您只需在页面中包含以下文件即可开始使用:
<script type="text/javascript" src="date.js"></script>
<script type="text/javascript" src="date-de-DE.js"></script>
修改强>
Date.js现在似乎已经死了,但Moment.js看起来是个不错的选择。