英文:
moving moment to dayjs in react
问题
在之前的代码中,我在我的React应用程序中使用了moment
,后来我改成了dayjs
。
在代码更改之前:
moment.duration(moment().diff(moment(timeString)));
在代码更改后:
dayjs.duration(dayjs().diff(dayjs(timeString)));
我遇到了这个错误:
dayjs.duration 不是一个函数
英文:
I was using moment in my react application earlier I changed to dayjs
before code:
moment.duration(moment().diff(moment(timeString)));
after code :
dayjs.duration(dayjs().diff(dayjs(timeString)));
I am getting this error:
dayjs.duration is not a function
答案1
得分: 1
Day.js没有内置Moment.js中的duration函数。然而,有一个名为"duration"的Day.js插件可以使用。
以下是如何使用该插件的步骤:
首先,你需要安装插件:
npm install dayjs duration
然后,在你的代码中,你需要导入并扩展Day.js:
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
// 现在你可以使用dayjs.duration
const diff = dayjs.duration(dayjs().diff(dayjs(timeString)));
请记住,只有当你想要使用duration函数时,才应该加载duration插件。
此外,要注意,在Day.js中处理持续时间时,API与Moment.js略有不同。例如,要获取以分钟为单位的持续时间,你应该使用diff.asMinutes()
,而不是diff.minutes()
。
英文:
Day.js doesn't have the duration function built-in as Moment.js does. However, there is a plugin for Day.js named duration which you can use.
Here's how you can use the plugin:
First, you need to install the plugin:
npm install dayjs duration
Then, in your code, you need to import and extend Day.js with it:
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)
// Now you can use dayjs.duration
const diff = dayjs.duration(dayjs().diff(dayjs(timeString)));
Remember, the duration plugin should be loaded whenever you want to use the duration function.
Also, be aware that when working with durations in Day.js, the API is slightly different from Moment.js. For example, to get the duration in minutes, you would use diff.asMinutes(), not diff.minutes().
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论