0

I want to check my type of variable, is it date. I want use angular.isDate() function.

If my variable have value "2016-08-10T08:38:49.397" angular.isDate() return false, what i can do?

<div ng-app="autoDrops" ng-controller="testController">
      {{isDate(date)}}
<div>

var autoDrops = angular.module('autoDrops', []);
autoDrops.controller('testController', function ($scope) {
        $scope.date = '2016-08-10T08:38:49.397'
    $scope.isDate = function(value){
        return angular.isDate(value);
    }
});

Example is on the (jsfiddle)

Jasmin Kurtic
  • 141
  • 12
  • 2
    `isDate` checks if the value is literally *an instance of `Date`*, not a string which can be interpreted as a date… – deceze Aug 17 '16 at 13:46
  • I'm not sure why you wouldn't just be doing this in the controller? Do you specifically want to show the result on the screen? in which case I would still keep the logic in the controller and just present the result through a controller property. – Rich Linnell Aug 17 '16 at 13:47
  • I know, but what is best solution for this problem, when you have datetime in string? – Jasmin Kurtic Aug 17 '16 at 13:47
  • Try [this method](http://stackoverflow.com/a/20972863/427146), you have to edit the regex though. It circumvents the usual pitfalls of leapyear dates and invalid dates which might be parsed into valid dates. – sabithpocker Aug 17 '16 at 14:04

1 Answers1

0

angular.isDate literally checks if the given value is an instance of Date. If you want to parse a string to see whether it contains a value that can be interpreted as date, use Date.parse:

> Date.parse('woeriug')
< NaN
> Date.parse('2016-08-10T08:38:49.397')
< 1470818329397

However, as MDN notes:

Parsing of strings with Date.parse is strongly discouraged due to browser differences and inconsistencies.

If you want more dependability, use a third party library that implements robust and browser-independent date parsing (or do it yourself).

deceze
  • 510,633
  • 85
  • 743
  • 889
  • If I use Date.parse I don't need angular.isDate because we can write code like [this](https://jsfiddle.net/5bL5tfo5/30/) – Jasmin Kurtic Aug 17 '16 at 14:13
  • Yup. You should not depend on Angular for handling dates, that's not what it's for. – deceze Aug 17 '16 at 14:16
  • problem in date.parse it is when you pass number, this function return valid date [example](https://jsfiddle.net/5bL5tfo5/31/). This not good decision. – Jasmin Kurtic Aug 17 '16 at 14:31
  • So what *do* you accept as a valid date and what don't you? Again, if you need more options and flexibility than Javascript offers you by default, there are many robust date parsing/handling/formatting/converting libraries out there. – deceze Aug 17 '16 at 14:33