-3

I'm getting my google api response for duration like 1 hour 13 minutes i need to covert this to 'hh:mm:ss' format.How to convert this in React js? response:

distance: {text: "47.8 km", value: 47790}
duration:
text: "1 hour 13 mins"
value: 4378
__proto__: Object
status: "OK"
sa_n__u
  • 336
  • 1
  • 9
  • This should get you started:: `duration.split(/[^\d]/).filter(x=>x!=="").map(n=>('0'+n).slice(-2))` – HMR Oct 11 '19 at 09:33
  • Possible duplicate of [JavaScript seconds to time string with format hh:mm:ss](https://stackoverflow.com/questions/6312993/javascript-seconds-to-time-string-with-format-hhmmss) – Yannick K Oct 11 '19 at 09:52
  • 1 hour 13 mins, is duration not time. So why trying to convert that to hh:mm:ss ? Surprising ? – Bilal Siddiqui Oct 11 '19 at 09:52
  • Just adding to @HMR comment, let timeArr = "1 hour 13 mins".split(/[^\d]/).filter(x=>x!=="").map(n=>('0'+n).slice(-2)).join(':'); Chained join(':') functionaal will give you 1:13: output. However there is huge scope to testcase handling. So I prefer to use this with in combination with momenjs as console.log(moment(timeArr, "h:mm").format("HH:mm:ss")); – Vipul Patil Oct 11 '19 at 10:05
  • @VipulPatil so `"1 hour 13 mins".split(/[^\d]/).filter(x=>x!=="").map(n=>('0'+n).slice(-2)).join(':');` gives you `1:13`? I want to know what browser you ran that code. – HMR Oct 11 '19 at 10:24
  • @HMR I'm using it on mozilla firefox, You can find it https://jsfiddle.net/vipul_patil/n0hp48by/3/ – Vipul Patil Oct 11 '19 at 12:51
  • @VipulPatil I get output of `01:13` in Firefox – HMR Oct 11 '19 at 13:02
  • @HMR , yeah I get that , its prefix '0'. Which I totally missed in my initial comment. – Vipul Patil Oct 11 '19 at 13:05

4 Answers4

2

It seems the values that are provided: 44790 and 4378, are meters and seconds. Now that you have the seconds as a number you can do all sort of things to get them in the format you want. There are a lot of javascript snippets out there that can do this for you:

function convertHMS(value) {
    const sec = parseInt(value, 10); // convert value to number if it's string
    let hours   = Math.floor(sec / 3600); // get hours
    let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
    let seconds = sec - (hours * 3600) - (minutes * 60); //  get seconds
    // add 0 if value < 10
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds; // Return is HH : MM : SS
}

const yourTime = convertHMS(4378); // 4378 seconds
// yourTime is 01:12:58
console.log(yourTime);

If you have a basic/beginning Javascript knowledge the only thing that might be funny business in this script are Math.floor() and parseInt().

credits to: https://www.4codev.com/javascript/convert-seconds-to-time-value-hours-minutes-seconds-idpx6943853585885165320.html in this case, you can find these ~10 lines anywhere though, I found them here after a few seconds of searching.

Always try to fix your problem in plain JS first before adding some sort of library that does the work for you, because you don't want to add a complete library for something that can be done in ~10 lines of plain JS. And ofcourse, plain JS works perfectly well in React =).

If you need to support IE6 - IE10 you might want to replace const and let with var (though I do not encourage supporting those browser if you don't have to from a business perspective).

edit: I'm fairly new to answering questions here so I converted the code to a code snippet.

Sapulidi
  • 76
  • 4
0

It is not related to React. You can simply use moment.js

moment(distance.value).format('hh:mm:ss');
ayming
  • 1
  • 1
0

You could either use one of the date formatting libraries (e.g. or ) or just calculate it by yourself. You are getting the duration in seconds (it seems to be 4378 seconds), so calculating it by yourself won't be much of an effort.

Here is an example:

const values = getHoursMinutesAndSeconds(4378);
console.log(values);
console.log(`${zeroPadding(values.hours, 2)}:${zeroPadding(values.minutes, 2)}:${zeroPadding(values.seconds, 2)}`);

function getHoursMinutesAndSeconds (totalSeconds) {
  // step 1: create seconds and hoursAndMinutes (minutes, but might be larger than 60)
  const hoursAndMinutes = Math.floor(totalSeconds / 60);
  const seconds = totalSeconds % 60;

  // step 2: create minutes and hours from hoursAndMinutes
  const hours = Math.floor(hoursAndMinutes / 60);
  const minutes = hoursAndMinutes % 60;

  return { hours, minutes, seconds };
}

function zeroPadding (number, length) {
  return String(number).padStart(length, '0');
}
ssc-hrep3
  • 15,024
  • 7
  • 48
  • 87
0

Great solution, Sapulidi. I used your code with a slight modification. Posting for anyone interested.

  • In typescript
  • Hours only appear if there are >0 hours

const millisecondsToHHMMSS = (duration: number) => {
  const sec = Math.round(duration / 1000);
  const hours = Math.floor(sec / 3600); // get hours
  const minutes = Math.floor((sec - hours * 3600) / 60); // get minutes
  const seconds = sec - hours * 3600 - minutes * 60; //  get seconds
  // add 0 if value < 10
  let sHours = hours > 0 ? `${hours}:` : '';
  let sMinutes = `${minutes}`;
  let sSeconds = `${seconds}`;

  if (minutes < 10) {
    sMinutes = '0' + sMinutes;
  }
  if (seconds < 10) {
    sSeconds = '0' + sSeconds;
  }
  return sHours + sMinutes + ':' + sSeconds;
  // Return is HH:MM:SS
};

let timeWithHours = 12345
let formattedWithHours = millisecondsToHHMMSS(timeWithHours)

let timeWithoutHours = 12345678
let formattedWithoutHours = millisecondsToHHMMSS(timeWithoutHours)

console.log(formattedWithHours)
console.log(formattedWithoutHours)
Jake Cronin
  • 1,002
  • 13
  • 15