1

Why the following code produces strange output (looks like moment().valueOf() returns 0)

Since 7 days ago : {{(moment().valueOf()  - 7*24*60*60*1000)  | date:'yyyy-MM-dd' }}

returns

Since 7 days ago : 1969-12-25
1
  • 1
    It would be easier to help you if you explained what you are trying to achieve. Even though I believe you are looking for something like this: moment(moment().valueOf() - 7*24*60*60*1000).format('YYYY-MM-DD'). You can bind this directly, without using AngularJS dateFilter. EDIT: Bixi's answer is definitely clearer. Commented Jun 4, 2014 at 7:28

2 Answers 2

2

You can do it with moment API :

moment().subtract('days', 7).format("YYYY-MM-DD")

Working jsfiddle : http://jsfiddle.net/D9UCF/1/

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

5 Comments

Thanks Bixi, don't know why nothing shows up when I try it! Here is the jsFiddle jsfiddle.net/D9UCF
Added fiddle. You can't use moment() like that in a template. One solution is to use a scope variable. Another one is to use a dedicated angular moment module like github.com/urish/angular-moment
May I know what it can't be used like that?
in angular template expressions you have to use angular mechanisms such as filters, operators, scope variable, etc ... see docs.angularjs.org/guide/expression
As a simple solution, you can expose moment trough the scope: $scope.moment = moment and I guess it would make your example work. Anyway, better to encapsulate the library in a dedicated service. See it here
2

This is because:

moment#valueOf simply outputs the number of milliseconds since the Unix Epoch, just like Date#valueOf.

[http://momentjs.com/docs/]

One way to achieve what you want is as follows:

Since 7 days ago: <span ng-bind="sevenDaysAgo"></span>

$scope.sevenDaysAgo = moment(new Date(new Date().setDate(new Date().getDate() - 7))).format('YYYY-MM-DD');

1 Comment

yeah, moment().valueOf() returns a number whilst angular's date filter works with Date objects

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.