I'm using the Time to X function of Moment.js. When the second parameter is true
, then the result is a day
. Is there a way to make this 1 day
through the API, or will I need to do a string replace?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You can use the string.replace method to replace "a day"
with "1 day"
.
Or you can try like this:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
var differenceInMillisec = a.diff(b);
var differenceInDays = a.diff(b, 'days'); //Output 1 day
回答2:
well, sometimes when the result is very simple, just go for it. a string replace is just one line of code... Even if there is a solution with the api, I'm sure it would be more "complicated" than doing a string replace... or just write a reusable function and call that function on the result like : replaceString(Time_to_X); where replaceString is a function using a string replace
回答3:
I've got a simple 100% solution to your question:
moment.localeData()._relativeTime.d = '1 day'; // override
console.log( moment.duration(1, 'days') ); // = '1 day', not 'a day'.
here's a fiddle with comments: https://jsfiddle.net/ichepurnoy/6bxujv8j/