Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 I've made to help you guys out. This is useful if you're coding a stopwatch, clock or anything like that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
161 views
Welcome To Ask or Share your Answers For Others

1 Answer

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,
};

const convertTime = (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}));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...