0

I wanted to convert seconds to hours using dateFormat nodejs package but it's not giving expected result.

My code :

import dateFormat from 'dateformat';

console.log(dateFormat(3600, "HH"));

Result:

when trying to convert 3600 secs to hrs then instead of giving output as 1 hr, it's giving output as 5 hrs

Vishal K.
  • 84
  • 9
  • No need to use plugin you can do it using simple javascript check this code https://stackoverflow.com/questions/37096367/how-to-convert-seconds-to-minutes-and-hours-in-javascript – Mayur Vaghasiya Jan 06 '22 at 11:14
  • I answer this question in this link: https://stackoverflow.com/a/69888278/10871558 – Mohmmaed-Amleh Jan 07 '22 at 12:33

1 Answers1

0

dateformat takes first argument as date and not the seconds. If you will convert 3600 to date then it is 52 years ago exact date is Thursday, 1 January 1970 06:30:00 GMT+05:30 in which hour is 5, which is showing to you. If you need to convert seconds to hours you can use this function

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}
Sahil Rajpal
  • 510
  • 4
  • 8