LeBlaireau
LeBlaireau

Reputation: 17467

Javascript formatting time - Date fns

I have a time that is stored in minutes as

01:30:00

I would like to display it as a nice human readable 1hr 30 minutes or 90 minutes.

What is the best way to achieve his I am using Date fns for the date but cannot get getminutes() method to work as it expects a full date.

https://date-fns.org/v1.28.0/docs/getMinutes.

Upvotes: 0

Views: 3650

Answers (3)

RobG
RobG

Reputation: 147363

You can just split into the parts and format using a suitable method. How much functionality you build into the parser/formatter depends on how many different formats of input and output you want to support.

You could write a much more general parser/formatter, but if you only need to support one format, something simple should do, e.g.

function formatTime(v) {
  var [h,m,s] = v.split(':').map(Number);
  return (h? h + ' hour' + (h != 1? 's' : '') : '') + 
         (m? ' ' + m + ' minute' + (m != 1? 's' : '') : '') +
         (s? ' ' + s + ' second' + (s != 1? 's' : '') : '');
}

['01:30:00', '21:01:05', '00:10:01', '16:00:08'].forEach(v =>
  console.log(v + ' => ' + formatTime(v))
); 

Upvotes: 0

Ankit
Ankit

Reputation: 671

let stringTime = '1:30:20';

let date = new Date (null, null, null, parseInt (stringTime.split(':')[0]), parseInt (stringTime.split(':')[1]), parseInt (stringTime.split(':')[2]));

let readiableTime = (((date.getHours()) ? date.getHours() + 'H' : '') + ' ' + (date.getMinutes() ? date.getMinutes() + 'm' : '')).trim();

console.log (readiableTime);

Answer: 1H 30m

Upvotes: 1

Alvaro Alves
Alvaro Alves

Reputation: 308

Check if this help you:

JS:

String.prototype.toHHMM = function () {
var sec_num = parseInt(this, 10); 
var hours   = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);

if (hours   < 10) {hours   = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+'hr(s) '+minutes+' minutes';

}

then:

alert('013000'.toHHMM());

https://codepen.io/alvaro-alves/pen/pZLwOd you will just to remove the ":" from time.

Upvotes: 1

Related Questions