Reputation: 1541
I'd like to set a default time for momentjs. For instance the default behavior is:
moment().format('YYYY-MM-DD') // returns current date
What I'd like to do is to override the current date to some other date, i.e. 2017-03-01, so whenever I do
moment().format('YYYY-MM-DD')
>> "2017-07-31"
Upvotes: 1
Views: 2809
Reputation: 12113
The Moment.js code calls new Date()
to initialize itself when the constructor is called without arguments (technically, it calls new Date(Date.now())
, but the result is the same). You have to pass something to get a specific date.
Of course, you could alter your local copy of the Moment.js library, but this is not recommended. You would have to keep it up-to-date with later releases of the libraries. And causing moment()
to return anything other than the current date would cause those looking back at your code to wonder what's going on.
Upon further investigation, it seems Moment.js does allow you to overwrite the implementation of moment.now()
which tells the rest of the library what time it is. See this article on the Moment.js website for more. There's an example there:
moment.now = function () {
return +new Date();
}
Which would be easy to alter for your needs:
moment.now = function () {
return +new Date(2017, 2, 1); // March 1st, 2017
}
I would strongly suggest using this technique sparingly (if at all) for the reasons given in the second paragraph above.
Upvotes: 3