将 “moving moment to dayjs in react” 翻译为中文: 将 Moment 迁移到 React 中的 Day.js

huangapple go评论103阅读模式
英文:

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().

huangapple
  • 本文由 发表于 2023年6月8日 15:47:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76429668.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定