4

im get date for ng-model like that

Thu May 21 2015 18:47:07 GMT+0700 (SE Asia Standard Time)

but it show me in console "TypeError: date.split is not a function" how to fix it?

   $scope.test = function(date) {
    console.log(date);
    $scope.d = (date.split(' ')[0]);
    $scope.m = (date.split(' ')[1]);
    $scope.y = (date.split(' ')[2]);
    $scope.dd = (date.split(' ')[3]);

}

2 Answers 2

5

The problem is that date is not a String, it's a Date object instance. So you can't use split on it. In order to use it you might want to convert it to String first. For example like his:

$scope.test = function(date) {
    date = date.toString();
    $scope.d = (date.split(' ')[0]);
    $scope.m = (date.split(' ')[1]);
    $scope.y = (date.split(' ')[2]);
    $scope.dd = (date.split(' ')[3]);    
};

When you console log it console.log(date); it calls toString automatically that's why it looked like a string for you.

Another thing, you really should not use split to extract data. Use methods of the Date object, like getMonth, .getFullYear, etc.

Sign up to request clarification or add additional context in comments.

Comments

0

Probably the date variable you get passed is not a string, but a Javascript Date object which has no split() method. You could go on and convert it to a string that you could split:

$scope.d = (date.toString().split(' ')[0]);

Which would work but not be very efficient, because the date would be composed to a string and then parsed again. Better would be using the properties of the date object itself:

$scope.d = date.getDate();
$scope.m = date.getMonth() + 1;
$scope.y = date.getFullYear();

and so on...

Find all the useable methods on the reference. Even better would be keeping the date itself as it is and just using the date properties where you need them in the view, for example:

<div class="myDate">Year: {{date.getFullYear()}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.