Moment JS diff功能在React Native中不起作用

时间:2019-07-01 12:56:16

标签: javascript node.js reactjs react-native momentjs

在我的本机应用程序中,我使用moment js。我有以下代码。

const expDate = moment(new Date(val)).format('MM-DD-YYYY');
const nowDate = moment().format('MM-DD-YYYY');
const diff = nowDate.diff(expDate, 'years');
console.log(diff);

但这表示diff不是函数。我尝试了其他几种方法,然后收到了弃用警告,说RFC2822,格式等。

上面的代码我在做什么错了?

2 个答案:

答案 0 :(得分:3)

我假设您的val是一个字符串,您可以通过传递格式直接从字符串中创建一个时刻。

const expDate = Moment("06-30-2018", "MM-DD-YYYY"); // create moment from string with format 
const nowDate = Moment(); // new moment -> today 
const diff = nowDate.diff(expDate, 'days'); // returns 366 
const diff2 = nowDate.diff(expDate, 'years'); // returns 1

.format将时刻转换为字符串,这就是.diff不起作用的原因

工作博览会:

https://snack.expo.io/@tim1717/cranky-bagel

答案 1 :(得分:2)

您需要在.format之后执行.diff

正确

    const expDate = moment(new Date("1999-02-18T00:00:00"));
    const nowDate = moment();
    const nowDateFormated = nowDate.format('MM-DD-YYYY');
    const expDateFormated = expDate .format('MM-DD-YYYY');
    const diff = nowDate.diff(expDate, 'years');
    console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    const expDate = moment(new Date("1999-02-18T00:00:00"));
    const nowDate = moment();
    const nowDateFormated = nowDate.format('MM-DD-YYYY');
    const expDateFormated = expDate .format('MM-DD-YYYY');
    const diff = nowDateFormated.diff(expDateFormated , 'years');
    console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>