用dayjs和React计算两个日期(天和月)之间的差异



我在逻辑上有点问题,我希望能够自动计算两个日期之间的天数和/或月份差异,例如:还剩20天,还剩1个月和17天。。。函数直接用dayjs实现这一点,而我似乎无法获得我想要的逻辑。

提前感谢您的帮助:(

暂时

let creation = dayjs(currentEstimate.createdAt)
let limit_date = dayjs(currentEstimate.createdAt).add(currentEstimate.estimate_validation_date, 'd')
let diff = dayjs(limit_date).diff(creation, 'd')
let months = diff / 31
if (months < 1){
console.log(`devis valable ${diff} jours`)
}else{
console.log(`devis valable ${months} mois`)
}

编辑

感谢Stephan Collins->


let duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
let relativeTime = require('dayjs/plugin/relativeTime')
dayjs.extend(relativeTime)
dayjs(currentEstimate.createdAt).to(dayjs(currentEstimate.createdAt).add(currentEstimate.estimate_validation_date, 'd'), true)
//one month

我有一个类似的问题,我想显示3 months and 5 days而不仅仅是3 months

我解决这个问题的方法是创建一个自定义插件,但我已经将其修改为这个问题的辅助函数。

const detailedRelativeTime = (date: Dayjs) => {
const now = dayjs()
const duration = dayjs.duration(date.diff(now))
// These values are whole numbers of each interval format
const durationInYears = duration.years()
const durationInMonths = duration.months()
const durationInDays = duration.days()
// We don't want to add suffixes to this variable since it will be used as the first part of modified outputs
const relativeDate = date.fromNow(true)
// Modify the years output if there is a year with at least 1 month
// Using !== 0 because values can be negative
if (durationInYears !== 0 && durationInMonths !== 0) {
// Add the remaining months from the current date to get the leftover relative time
// We use add() instead of subtract() because the duration variable can be negative if necessary
const relativeLeftoverMonths = now.add(durationInMonths, 'months').fromNow()
// e.g. 1 year and 5 months ago
return relativeDate + ' and ' + relativeLeftoverMonths
}
// Modify the months output if there is a month with at least 1 day
if (durationInMonths !== 0 && durationInDays !== 0) {
const relativeLeftoverDays = now.add(durationInDays, 'days').fromNow()
// e.g. 1 month and 5 days ago
return relativeDate + ' and ' + relativeLeftoverDays
}
// There were no durations that need to be added, so just return the default relative date
return date.fromNow()
}

你可以这样使用这个功能:

detailedRelativeTime(dayjs('2019-01-01')) // 4 years and 4 months ago (at the time of writing)

**通过日期中的最大日期和最小日期**

enter code here

const-minDate=新日期("2022-03-03"(;const maxDate=新日期("2023-03-03"(;

设dD=数学下限(新日期(maxDate-minDate(/(1000*60*60*24((

设mD=maxDate.getMonth((-minDate.getMonth((

让myD=maxDate.getYear((-minDate.getYear((

设yD=0

如果(myD>0({yD=myD*12}

mD+=yDconsole.log(dD(console.log(mD(console.log(myD(

相关内容

  • 没有找到相关文章

最新更新