我的逻辑有点问题,我希望能够自动计算两个日期之间天数和/或月数的差异,例如:还剩 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`)
}
编辑
感谢斯蒂芬柯林斯 ->
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 = new Date("2022-03-03"); const maxDate = new Date("2023-03-03");
let dD = Math.floor(new Date(maxDate - minDate) / (1000 * 60 * 60 * 24 ))
让 mD = maxDate.getMonth() - minDate.getMonth()
让 myD = maxDate.getYear() - minDate.getYear()
设 yD = 0
if(myD > 0){yD=myD*12}
mD += yD console.log(dD)console.log(mD)console.log(myD)