Home > Software design >  Is there a way in JavaScript to convert a number of seconds into a string such as "5 h 20 min&q
Is there a way in JavaScript to convert a number of seconds into a string such as "5 h 20 min&q

Time:08-29

Is there a way in JavaScript to convert a number of seconds into a string such as "5 h 20 min", and have it localised with the new Intl functions that were introduced into JavaScript, so in German you would have "5 Std" instead of "5 h"? I found such snippets for relative time format, but found nothing for absolute time formatted.

CodePudding user response:

You could use the Date constructor with a fixed date and use the seconds parameter for your time data. Then use the get-functions of the date to get the hour/minute/second values.

To get the data localized read the browser language from navigator.language, take the first two letters as identifier and built an object map containing the translations (example in the code). Keep in mind that you need a fallback if your translation map does not contain the browser language.

let translations = [
  { lang: 'en', hours: 'h', minutes: 'min', seconds: 's' },
  { lang: 'de', hours: 'std', minutes: 'min', seconds: 'sek' }
];

let t = new Date(1970 /*year*/, 1/*month*/, 1/*day*/, 0/*hours*/, 0/*minutes*/, 623 /* seconds, the interisting part */, 0 /*milliseconds*/);
let result = t.getHours()   'h '   t.getMinutes()   'min '   t.getSeconds()   's';
console.log(result);

CodePudding user response:

Below you can see how toLocaleTimeString can be used in simple examples.

let fullSeconds = 8000; //example value
let hours = parseInt(fullSeconds / 3600);
fullSeconds %= 3600;
let minutes = parseInt(fullSeconds / 60);
let seconds = fullSeconds % 60;
let dt = new Date(1970, 1, 1, hours, minutes, seconds);
console.log(dt.toLocaleTimeString('en-US'));
console.log(dt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }))

You will need to look into the documentation of toLocaleTimeString and experiment with its use-cases to see whether it fits your requirements. If not, then you can always implement your own date formatting functions.

  • Related