2

I just try to check a string whether a date or not. This is my code in angular JS.

var mydt= "2015/07/29"; 
document.write(angular.isDate(mydt));

This always return false. But actually this is a date.

But when I try this code,

var cur_date = new Date(); 
document.write(cur_date);    
document.write(angular.isDate(cur_date)); 

The executed result is,

Wed Jul 29 2015 15:15:13 GMT+0530 (Sri Lanka Standard Time) true

I'm wondering why we cannot check simple date format like "yyyy/mm/dd" in simple way.

John Slegers
  • 45,213
  • 22
  • 199
  • 169
weeraa
  • 1,123
  • 8
  • 23
  • 40

2 Answers2

4

angular.isDate() checks if the input is of type Date. Function source from AngularJS

function isDate(value) {
  return toString.call(value) === '[object Date]';
}

That's why angular.isDate returned true on a Date object, but false on a string.

var d = new Date('7/29/2015');
alert(angular.isDate(d)); // Alerts true on the date object
alert(d.toString()); // Alerts the string value of the date object
alert(angular.isDate(d.toString())); // Alerts false on the string value

jsfiddle

You can use Date.parse():

Check if a string is a date value

Community
  • 1
  • 1
Guy
  • 1,547
  • 1
  • 18
  • 29
0
function isValidDate(dateString) {
  var regEx = /^\d{4}-\d{2}-\d{2}$/;
  return dateString.match(regEx) != null;
}

check if string contains number four-two-two

Ami Patel
  • 296
  • 1
  • 13