dayjs icon indicating copy to clipboard operation
dayjs copied to clipboard

Format duration, leave out / escape months and add it to days amount

Open warri93 opened this issue 3 years ago • 7 comments

Describe the bug Formatting a duration does not have the ability to escape months. Instead it just ignores them

For example we want to display PT11856H8M34S as years, days, hours, minutes & seconds. Leaving out the months.

dayjs.duration('PT11856H8M34S').add(0,'s').format('Y[y] D[d] H[h] m[m]') Output: 1y 9d 0h 8m

dayjs.duration('PT11856H8M34S').add(0,'s').format('Y[y] M[m] D[d] H[h] m[m]') Output: 1y 4m 9d 0h 8m

You can clearly see that we lose 4 months of days... How can we prevent this? It should output something like 1y 129d 0h 8m

Expected behavior Adding months to days value

Information

  • Day.js Version 1.11.2

warri93 avatar May 13 '22 12:05 warri93

@iamkun

warri93 avatar May 13 '22 12:05 warri93

need this too

baixiaoyu2997 avatar Jun 02 '22 07:06 baixiaoyu2997

The formatting of durations is similar to the formatting of dates: if you have a date like 2022-06-23T13:14:15 and format it with a format string YYYY-DD HH:mm:ss the month is not part of the output.
The same goes with duration: if you omit the M part, then the output will not include the months (and will not convert it to days, or hours or any other unit included in the output). Perhaps the documentation can be misinterpreted.

Using the asDays() function will get the duration as days - but only the whole duration (see documentation).

BePo65 avatar Jun 07 '22 18:06 BePo65

DD max 31 day, for duration, i need like 80day 23h 30m

baixiaoyu2997 avatar Jun 08 '22 01:06 baixiaoyu2997

That's what I understand, but dayjs cannot do that using format. You could create a small function that gets the values you need, e.g. like this:

const durationDayjs = dayjs.duration('PT11856H8M34S').add(0, 's')

const years = Math.floor(durationDayjs.asYears())  // 1
const days = Math.floor(durationDayjs.asDays()) - (years * 365)  // 129
const hoursWithFraction = (durationDayjs.asDays() % 1) * 24
const hours = Math.floor(hoursWithFraction) * 24  // 0
const minutes = Math.floor((hoursWithFraction % 1) * 60)
const seconds = durationDayjs.asSeconds() % 60  // 34
 :
 :

BePo65 avatar Jun 08 '22 04:06 BePo65

thank for reply ,i already did something like this :satisfied:

baixiaoyu2997 avatar Jun 08 '22 06:06 baixiaoyu2997

of course you did 😁

BePo65 avatar Jun 08 '22 06:06 BePo65