riotgear
riotgear

Reputation: 555

angular momentjs date issues

I am having a heck of a time trying to generate dates using moment.js inside of angular. I just want to create random dates and I don't have any clue as to how.

I've looked through http://momentjs.com/ but I don't know how to convert the js to the angular format.

Here is the link

http://jsfiddle.net/galnova/Pe2Zc/150/

If you look below you can see a snippet here.

Here is the snippet

var app = angular.module("app", []);

app.constant("moment", moment);

app.controller("ctrl", function($scope, moment) {
    $scope.d = new Date();
    $scope.date = new moment();
    $scope.date2 = moment().add('days', 7); 
});

Here is the html

<div ng-app="app" ng-controller="ctrl">

    {{ date }} <br/> <br/>

    {{ date2 }} <br/> <br/>

    {{d | date: 'MMM-dd-yyyy'}} <br/> <br/>

    {{d | date: 'MMM-dd-yyyy'}}

</div>

Upvotes: 0

Views: 566

Answers (4)

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

It is working now, check this

https://jsbin.com/wohucud/edit?html,js,output

app.controller("ctrl", function($scope, moment) {
    $scope.getRandomDate = function(){
        var year = Math.floor(Math.random() * 2) + 2015;
        var month = Math.floor(Math.random() * 12) ;
        var day = Math.floor(Math.random() * 31);
        return moment([year, month, day]).toDate();
   };
   $scope.date = $scope.getRandomDate(); 

});

And also give some credit to @Leandro

Upvotes: 1

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

You are already using moment. You can use angular-moment for date filters and much more. https://github.com/urish/angular-moment

Upvotes: 0

Zohaib Ijaz
Zohaib Ijaz

Reputation: 22875

I have updated the fiddle

http://jsfiddle.net/Pe2Zc/152/

$scope.getRandomDate = function(){
    var year = Math.round(Math.random() * 6) + 2015;
    var month = Math.round(Math.random() * 13) ;
    var day = Math.round(Math.random() * 32);
    return moment([year, month, day]);
}

Upvotes: 2

Leandro
Leandro

Reputation: 67

Try to use .toDate()

$scope.date = new moment().toDate()

Upvotes: 0

Related Questions