javascript - Moment js diff函数在 native react 中不起作用

标签 javascript node.js reactjs react-native momentjs

在我的 React Native 应用程序中,我使用了 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、格式等。

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

最佳答案

我假设你的 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

关于javascript - Moment js diff函数在 native react 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56836141/

相关文章:

javascript - React-Router ^2.4.0 错误。亲属路线找不到元素

javascript - HTML Form onsubmit 不执行外部函数

android - 如何验证android帐单收据服务器端

node.js - 在 ubuntu 16 上使用 npm 安装生成器-jhipster 时出错

javascript - 用户刷新页面时如何使Javascript文件不重置

javascript - 如何确保 React 组件的状态正确?

reactjs - ReactJS 中生产和开发构建的区别

javascript - 使用严格模式时如何从 JavaScript 对象中删除属性

javascript - 如何在iOS的uiwebview中检测整个body元素的onclick事件?

php - 如何记录可变数量的参数