Home > front end >  Converting seconds to hours using dateFormat npm package giving incorrect result
Converting seconds to hours using dateFormat npm package giving incorrect result

Time:01-06

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

CodePudding user response:

fun getDateString(seconds: Long, outputPattern: String): String {
        try {
            val dateFormat = SimpleDateFormat(outputPattern,Locale.ENGLISH)
            val calendar = Calendar.getInstance()
            calendar.timeInMillis = seconds * 1000
            val date = calendar.time
            return dateFormat.format(date)
        } catch (e: Exception) {
            Log.e("utils", "Date format", e)
            return ""
        }
    }

CodePudding user response:

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;
}
  •  Tags:  
  • Related