blankpage
blankpage

Reputation: 137

Moment.js convert x minutes to y hours z minutes

So I have a number, for instance 90. what I want to do is convert it to "1 hr 30 mins". I have tried this:

moment.utc(
    moment.duration(90, "minutes")
    .asMilliseconds()
).format("h:mm")

This returns 1:30.

If it do this,

moment.utc(
    moment.duration(90, "minutes")
    .asMilliseconds()
).format("h [hour] mm [minutes]")

, then I get 1 hour 30 minutes.

This is great, but if I plug in 180, then I get 3 hour 00 minutes, but it should be 3 hours. The 00 minutes should be omitted, and hour should be hours when the number of hours is greater than 1. The same goes for minutes.

Is this possible with moment.js?

Upvotes: 2

Views: 1570

Answers (2)

I don't think its possible with momemt js.

We have to construct the format dynamically based on the hour and minute value we get. Please check the code below.

input=180;

hour=Math.floor(input/60);
min=input%60;
format = "";
//console.log(hour);
//console.log(min);
if (hour>1 && min>1)
    format = "h [hours] mm [minutes]";
else if (hour>1 && min==1)
    format = "h [hours] mm [minute]";
else if (hour>1 && min==0)
    format = "h [hours]";
else if( hour==0 && min>1)
    format = "m [minutes]";
else if (hour==0 && min<=1)
    format = "mm [minute]";
else
    format="";
//console.log(format);

moment.utc(
    moment.duration(input, "minutes")
    .asMilliseconds()
).format(format)

Upvotes: 1

technophyle
technophyle

Reputation: 9128

You can just write a bit of custom code to solve the problem, like this:

const time1 = moment.utc(
  moment.duration(180, "minutes")
  .asMilliseconds()
)

const time2 = moment.utc(
  moment.duration(90, "minutes")
  .asMilliseconds()
)

function formatTime(time) {
  const minutes = time.minutes();
  const hours = time.hours();
  const hourFormatStr = hours === 1 ? 'hour' : 'hours';
  const minuteFormatStr = minutes === 1 ? 'minute' : 'minutes';
  if (!time.minutes()) {
    return time.format(`h [${hourFormatStr}]`);
  }
  return time.format(`h [${hourFormatStr}] mm [${minuteFormatStr}]`);
}

console.log(formatTime(time1));
console.log(formatTime(time2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Also, I found this library, which seems to do the job you want.

Upvotes: 2

Related Questions