Javascript - 将 DD:HH:MM:SS 转换为毫秒 [英] Javascript - Convert DD:HH:MM:SS to milliseconds
问题描述
我见过很多转换日期的函数,但找不到任何关于如何将 Days:Hours:Minutes:Seconds 转换为毫秒的具体信息.
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.
推荐答案
通常我看到这是在不使用实用程序函数的情况下内联完成的,但是如果您要创建一个实用程序,让我们使其具有可扩展性.
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.
我不同意
Array
的论点,很难记住什么代表什么.除非你只做天/小时/分钟/秒,否则这可能会让人感到困惑.此外,除非您总是使用每个参数,否则这会变得很麻烦.
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.
零值是不正确的(为任何值传递 0 会导致它不正确)
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}));
这篇关于Javascript - 将 DD:HH:MM:SS 转换为毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!