Search code examples
javascriptdatetimetime-format

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.


Solution

  • 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.