Skip to content Skip to sidebar Skip to footer

Javascript - Convert Dd:hh:mm:ss To Milliseconds

I've seen a lot of functions to convert dates around but couldn't find anything specific on how to convert Days:Hours:Minutes:Seconds to milliseconds. So here is a basic function

Solution 1:

Normally I've seen this done inline without using a utility function, but if you're going to create a util let's make it extensible.

  1. I disagree with the arguments Array, it's difficult to remember what represents what. Unless you're only doing day/hour/minute/second, this can get confusing. Additionally, unless you're always using every parameter this becomes cumbersome.

  2. It's incorrect for zero values (passing 0 for any value causes it to be incorrect)

const conversionTable = {
  seconds: 1000,
  minutes: 60*1000,
  hours: 60*60*1000,
  days: 24*60*60*1000,
};

constconvertTime = (opts) => 
  Object.keys(opts).reduce((fin, timeKey) => (
    fin + opts[timeKey] * conversionTable[timeKey]
  ), 0)

console.log(convertTime({
  days: 5,
  hours: 4,
  minutes: 2,
  seconds: 19,
}));

console.log(convertTime({seconds: 1}));

Solution 2:

functionconvertDhms(d,h,m,s){
    d <= 0 ? d=1 : d=d*24*60*60*1000;
    h <= 0 ? h=1 : h=h*60*60*1000;
    m <= 0 ? m=1 : m=m*60*1000;
    s <= 0 ? s=1 : s=s*1000;

    return d + h + m + s;
  }

Usage:

var finalDate = convertDhms(5, 4, 2, 19); /* will convert 5 days, 4 hours, 2 minutes and 19 seconds to miliseconds. Keep in mind that the limit to hours is 23, minutes 59 and seconds 59. Days have no limits. */

Solution 3:

I suppose a simple solution is to use the Date object's parse method, which gives back the milliseconds of the object. The catch is that it's meant to return the time from the UNIX Epoch time.

// see docs for Date constructorconst baseDate = newDate(0,0,0,0,0,0,0);
const baseMS = Date.parse(baseDate);

// base milliseconds is not zero// it defaults to a day before Jan 1, 1970 in msconsole.log(baseMS);

functionconvertToMS(dy,hr,mn,s,ms) {
  const date = newDate(0,0,dy,hr,mn,s,ms);
  const dateMS = Date.parse(date);
  return dateMS - baseMS;
}

// one day in millisecondsconsole.log(convertToMS(1,0,0,0,0));
console.log(24 * 60 * 60 * 1000);

P.S. I don't quite understand the logic behind why a new Date object with zero in all parameters returns a large negative value, but we have to account for that in the code.

EDIT: Since there's is a discrepancy between the number of days in each month, and days in each year, it's better to not have year and months in the input of the function convertToMS.

Post a Comment for "Javascript - Convert Dd:hh:mm:ss To Milliseconds"