检测一个;无效日期“;JavaScript中的日期实例
我想说明JS中有效日期对象和无效日期对象之间的区别,但不知道如何:检测一个;无效日期“;JavaScript中的日期实例,javascript,date,Javascript,Date,我想说明JS中有效日期对象和无效日期对象之间的区别,但不知道如何: var d = new Date("foo"); console.log(d.toString()); // shows 'Invalid Date' console.log(typeof d); // shows 'object' console.log(d instanceof Date); // shows 'true' 编写isValidDate函数有什么想法吗 Ash建议使用Date.parse解析日期字符串,它提
var d = new Date("foo");
console.log(d.toString()); // shows 'Invalid Date'
console.log(typeof d); // shows 'object'
console.log(d instanceof Date); // shows 'true'
编写isValidDate
函数有什么想法吗
- Ash建议使用
解析日期字符串,它提供了一种权威的方法来检查日期字符串是否有效Date.parse
- 如果可能的话,我更愿意让我的API接受一个日期实例,并能够检查/断言它是否有效。Borgar的解决方案可以做到这一点,但我需要跨浏览器进行测试。我还想知道是否有更优雅的方式 <> Li >艾熙让我认为没有API接受<代码>日期<代码>实例,这将是最容易验证的。
- Borgar建议测试
实例,然后测试日期
的时间值。如果日期无效,则时间值为日期
。我检查了一下,这个行为符合标准,这正是我想要的NaN
新日期()
您应该使用:
var timestamp = Date.parse('foo');
if (isNaN(timestamp) == false) {
var d = new Date(timestamp);
}
Date.parse()
返回时间戳,这是一个整数,表示自1970年1月1日以来的毫秒数。如果无法解析提供的日期字符串,它将返回NaN
。我将这样做:
if (Object.prototype.toString.call(d) === "[object Date]") {
// it is a date
if (isNaN(d.getTime())) { // d.valueOf() could also work
// date is not valid
} else {
// date is valid
}
} else {
// not a date
}
更新[2018-05-31]:如果您不关心来自其他JS上下文(外部窗口、框架或iFrame)的日期对象,则最好使用这种更简单的形式:
function isValidDate(d) {
return d instanceof Date && !isNaN(d);
}
您可以通过以下方式检查
日期
对象d
的有效性
d instanceof Date && isFinite(d)
为了避免跨帧问题,可以将instanceof
检查替换为
Object.prototype.toString.call(d) === '[object Date]'
调用中的
getTime()
是不必要的,因为isNaN()
和isFinite()
都会隐式转换为数字。我非常喜欢Christoph的方法(但没有足够的声誉来投票支持它)。
对于我的使用,我知道我总是有一个Date对象,所以我只是用一个有效的()方法扩展了Date
现在我可以写这个了,它比在代码中检查isFinite更具描述性
d = new Date(userDate);
if (d.valid()) { /* do stuff */ }
很好的解决方案!包含在我的辅助函数库中,现在看起来如下所示:
Object.isDate = function(obj) {
/// <summary>
/// Determines if the passed object is an instance of Date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.prototype.toString.call(obj) === '[object Date]';
}
Object.isValidDate = function(obj) {
/// <summary>
/// Determines if the passed object is a Date object, containing an actual date.
/// </summary>
/// <param name="obj">The object to test.</param>
return Object.isDate(obj) && !isNaN(obj.getTime());
}
Object.isDate=函数(obj){
///
///确定传递的对象是否为日期的实例。
///
///要测试的对象。
返回Object.prototype.toString.call(obj)='[Object Date]';
}
Object.isValidDate=函数(obj){
///
///确定传递的对象是否为包含实际日期的日期对象。
///
///要测试的对象。
返回Object.isDate(obj)&&!isNaN(obj.getTime());
}
受Borgar方法的启发,我已确保代码不仅验证日期,而且实际确保日期是真实日期,这意味着不允许日期为2011年9月31日和2011年2月29日
function(dateStr) {
s = dateStr.split('/');
d = new Date(+s[2], s[1]-1, +s[0]);
if (Object.prototype.toString.call(d) === "[object Date]") {
if (!isNaN(d.getTime()) && d.getDate() == s[0] &&
d.getMonth() == (s[1] - 1)) {
return true;
}
}
return "Invalid date!";
}
我使用以下代码验证年、月和日期的值
function createDate(year, month, _date) {
var d = new Date(year, month, _date);
if (d.getFullYear() != year
|| d.getMonth() != month
|| d.getDate() != _date) {
throw "invalid date";
}
return d;
}
有关详细信息,请参阅。您可以使用此scirpt检查txDate.value的有效格式。如果格式不正确,则不会实例化日期obejct,并将null返回给dt
var dt = new Date(txtDate.value)
if (isNaN(dt))
正如@MiF在短时间内建议的那样
if(isNaN(new Date(...)))
以上所有解决方案对我都不起作用,但起作用的是
函数有效期(d){
var日期=新日期(d);
var day=”“+date.getDate();
如果(day.length==1)day=“0”+天;
var month=“”+(date.getMonth()+1);
如果(月长==1)月=0“+月;
var year=”“+date.getFullYear();
回报率((月+“/”+日+“/”+年)=d);
}
上面的代码将看到,当JS将2012年2月31日改为2012年2月3日时,它是无效的在尝试验证日期(如2012年2月31日)时,这些答案对我都不起作用(在Safari 6.0中进行了测试),但是,在尝试任何大于2012年2月31日的日期时,它们都可以正常工作 所以我不得不使用暴力。假设日期的格式为
mm/dd/yyyy
。我正在使用@broox答案:
Date.prototype.valid = function() {
return isFinite(this);
}
function validStringDate(value){
var d = new Date(value);
return d.valid() && value.split('/')[0] == (d.getMonth()+1);
}
validStringDate("2/29/2012"); // true (leap year)
validStringDate("2/29/2013"); // false
validStringDate("2/30/2012"); // false
我的解决方案是简单地检查您是否获得了有效的日期对象: 实施 用法
我想提到的是,jQueryUIDatePicker小部件有一个非常好的日期验证器实用程序方法,用于检查格式和有效性(例如,不允许使用01/33/2013日期) 即使您不想将页面上的datepicker小部件用作UI元素,也可以将其.js库添加到页面中,然后调用validator方法,将要验证的值传递给它。为了让事情变得更简单,它将字符串作为输入,而不是JavaScript日期对象 见: 它没有作为方法列出,但它作为一个实用函数存在。在页面中搜索“parsedate”,您将发现: $.datepicker.parseDate(格式、值、设置)-使用指定格式从字符串值中提取日期 用法示例: (有关重新指定日期格式的详细信息,请访问) 在上面的示例中,您不会看到警报消息,因为“01/03/2012”是指定格式的日历有效日期。但是,例如,如果将“stringval”设置为“13/04/2013”,则会收到警报消息,因为值“13/04/2013”无效
如果成功解析传入的字符串值,“testdate”的值将是表示传入字符串值的Javascript日期对象。如果不是,它将是未定义的。日期对象到字符串是检测两个字段是否都是有效日期的更简单、更可靠的方法。 e、 g.如果在日期输入字段中输入“-----”。上面的一些答案行不通
jQuery.validator.addMethod("greaterThan",
function(value, element, params) {
var startDate = new Date($(params).val());
var endDate = new Date(value);
if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') {
return false;
} else {
return endDate > startDate;
}
},'Must be greater than {0}.');
您只需使用
以下是一个例子:
var m = moment('2015-11-32', 'YYYY-MM-DD');
m.isValid(); // false
文档中的内容非常清楚
此外,以下解析标志会导致无效日期:
:日期字段溢出,如第13个月、当月第32天(或非闰年的2月29日)、一年中第367天等。溢出包含溢出
Date.prototype.isValid = function () { // An invalid date object returns NaN for getTime() and NaN is the only // object not strictly equal to itself. return this.getTime() === this.getTime(); };
var d = new Date("lol"); console.log(d.isValid()); // false d = new Date("2012/09/11"); console.log(d.isValid()); // true
IsValidDate: function(date) { var regex = /\d{1,2}\/\d{1,2}\/\d{4}/; if (!regex.test(date)) return false; var day = Number(date.split("/")[1]); date = new Date(date); if (date && date.getDate() != day) return false; return true; }
var stringval = '01/03/2012'; var testdate; try { testdate = $.datepicker.parseDate('mm/dd/yy', stringval); // Notice 'yy' indicates a 4-digit year value } catch (e) { alert(stringval + ' is not valid. Format must be MM/DD/YYYY ' + 'and the date value must be valid for the calendar.'; }
jQuery.validator.addMethod("greaterThan", function(value, element, params) { var startDate = new Date($(params).val()); var endDate = new Date(value); if(startDate.toString() === 'Invalid Date' || endDate.toString() === 'Invalid Date') { return false; } else { return endDate > startDate; } },'Must be greater than {0}.');
var m = moment('2015-11-32', 'YYYY-MM-DD'); m.isValid(); // false
var is_valid_date = function(year, month, day) { var d = new Date(year, month - 1, day); return d.getFullYear() === year && (d.getMonth() + 1) === month && d.getDate() === day };
is_valid_date(2013, 02, 28) && is_valid_date(2016, 02, 29) && !is_valid_date(2013, 02, 29) && !is_valid_date(0000, 00, 00) && !is_valid_date(2013, 14, 01)
if(!isNaN(new Date("2012/25/255").getTime())) return 'valid date time'; return 'Not a valid date time';
new Date('foo') == 'Invalid Date'; //is true
new Date('foo') === 'Invalid Date'; //is false
function isValidDate(str) { var parts = str.split('/'); if (parts.length < 3) return false; else { var day = parseInt(parts[0]); var month = parseInt(parts[1]); var year = parseInt(parts[2]); if (isNaN(day) || isNaN(month) || isNaN(year)) { return false; } if (day < 1 || year < 1) return false; if(month>12||month<1) return false; if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && day > 31) return false; if ((month == 4 || month == 6 || month == 9 || month == 11 ) && day > 30) return false; if (month == 2) { if (((year % 4) == 0 && (year % 100) != 0) || ((year % 400) == 0 && (year % 100) == 0)) { if (day > 29) return false; } else { if (day > 28) return false; } } return true; } }
QUnit.test( "valid date test", function( assert ) { //The following are counter-examples showing how the Date object will //wrangle several 'bad' dates into a valid date anyway assert.equal(isValidDate(new Date(1980, 12, 15)), true); d = new Date(); d.setFullYear(1980); d.setMonth(1); d.setDate(33); assert.equal(isValidDate(d), true); assert.equal(isValidDate(new Date(1980, 100, 150)), true); //If you go to this exterme, then the checker will fail assert.equal(isValidDate(new Date("This is junk")), false); //This is a valid date string assert.equal(isValidDate(new Date("November 17, 1989")), true); //but is this? assert.equal(isValidDate(new Date("November 35, 1989")), false); //Ha! It's not. So, the secret to working with this version of //isValidDate is to pass in dates as text strings... Hooboy //alert(d.toString()); });
function isValidDate(input) { if(!(input && input.getTimezoneOffset && input.setUTCFullYear)) return false; var time = input.getTime(); return time === time; };
function isValidDate(strDate) { var myDateStr= new Date(strDate); if( ! isNaN ( myDateStr.getMonth() ) ) { return true; } return false; }
isValidDate(""2015/5/2""); // => true isValidDate(""2015/5/2a""); // => false
angular.isDate(myDate);
if(!isNaN(date.getTime()))
/** * Check if date exists and is valid. * * @param {String} dateString Date in YYYY-mm-dd format. */ function isValidDate(dateString) { var isValid = false; var date; date = new Date( dateString); if ( Object.prototype.toString.call( date) === "[object Date]") { if (isNaN(date.getTime())) { // Date is unreal. } else { // Date is real if month and day match each other in date and string (otherwise may be shifted): isValid = date.getUTCMonth() + 1 === dateString.split("-")[1] * 1 && date.getUTCDate() === dateString.split("-")[2] * 1; } } else { // It's not a date. } return isValid; }
Date.prototype.isValid = function (d) { return !isNaN(Date.parse(d)) } ;
Date.prototype.isValid = d => !isNaN(Date.parse(d));
function isValidDate(d) { try { d.toISOString(); return true; } catch(ex) { return false; } }
Symbol.for(new Date("Peter")) === Symbol.for("Invalid Date") // true Symbol.for(new Date()) === Symbol.for("Invalid Date") // false