![](/img/trans.png)
[英]How can I format time using moment.js in React JS and webpack
[英]Problem using NPM Moment.js in React: moment__WEBPACK_IMPORTED_MODULE_2__format is not a function?
编辑:我已经使用dateFns(date-fns.org)解决了我的问题,但是我很想知道如何在这里使用Momentjs。
我使用create-react-app
创建了一个应用,并尝试使用一种格式将当前数据转换为字符串。 我收到以下错误,但是
moment__WEBPACK_IMPORTED_MODULE_2__format不是函数
当我尝试运行此代码时
import moment from 'moment'
const today = moment().calendar().format('DD-MM-YYY')
const tomorrow = moment().add(1, 'days').calendar().format('DD-MM-YYY')
this.setState({checkin:today,checkout:tomorrow})
我进行了一些谷歌搜索,发现了诸如https://github.com/moment/moment/issues/4229之类的页面,其中一个建议是尝试
import * as moment from 'moment'
但这也无济于事。
我也试过
import * as moment from 'moment/moment'
这是另一个建议,但也没有用。
即使只是打电话
moment.format('DD-MM-YYY')
引发相同的错误。
我的package.json
具有这些依赖关系
"dependencies": {
"moment": "^2.24.0",
"react": "^16.8.6",
"react-datetime": "^2.16.3",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1"
},
我在这里茫然不知所措。 任何帮助,不胜感激!
尝试这个:
const today = moment(moment().calendar()).format('DD-MM-YYY')
const tomorrow = moment(moment().add(1, 'days').calendar()).format('DD-MM-YYY')
我假设.calender()
将返回一个string
,如果我们需要将其解析为特定格式,则需要将其作为参数传递给另一个moment
实例,然后对其应用format
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.