Formatting time

Alex Lord
Alex Lord used Ask the Experts™
on
Dev Question

So i have this data coming from a table which is a time 00:03:22.

how can i format this in js to the user to be like 3min 22 seconds ?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Zakaria AcharkiAnalyst Developer
Distinguished Expert 2018

Commented:
I suggest to you the use of MomentJS Library that allows you to simply Parse, validate, manipulate, and display dates and times in JavaScript.
ste5anSenior Developer

Commented:
Just a comment: don't mix time with time spans. They are different data types.

Your given data looks like time, but a formatting in minutes and seconds denotes a time span. E.g. 11:35:22 vs. 695min 22sec.

Author

Commented:
okay so how do i do that ? moments is time span
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

ste5anSenior Developer

Commented:
Hae? Time spans in MomentJS are called durations.
Analyst Developer
Distinguished Expert 2018
Commented:
If you don't want to use any extra library you could use the following function :

function humanizeTime(time) {
  var timeParts = time.split(':');
  var hours = Number(timeParts[0]);
  var minutes = Number(timeParts[1]);
  var seconds = Number(timeParts[2]);
  var huminizedTime = [];

  if (hours > 0) {
    huminizedTime.push(hours + (hours > 1 ? ' Hours' : ' Hour'));
  }
  if (minutes > 0) {
    huminizedTime.push(minutes + (minutes > 1 ? ' Minutes' : ' Minute'));
  }
  if (seconds > 0) {
    huminizedTime.push(seconds + (seconds > 1 ? ' Seconds' : ' Second'));
  }

  return huminizedTime.join(' ');
}

Open in new window

Working live sample

So just pass your time as a string like :

humanizeTime('00:03:22'); //3 Minutes 22 Seconds

Open in new window


NOTE : That will give you more flexibility to change the strings "Hour/Minute/Second" as in your question for example you want "3 min" instead of "3 Minutes" you could adjust it inside the function...
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
Question
How do you want this to be displayed
12:00:22
Or this
12:23:00
Howard BashSenior Software Engineer

Commented:
If you guarantee that the incoming format is hh:mm:ss then you could use the split function and build the string.  That would be the simpliest way ASSUMING the format is as stated.
ste5anSenior Developer

Commented:
hmm, Howard's answer makes me think:

@Alex: Do you have a time, thus a Date, or a string?

Author

Commented:
it only a string this time

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial