简体   繁体   English

如果在Javascript中指定了十进制时间,如何计算最接近的整个时间单位

[英]How to calculate nearest whole time unit if a decimal time is specified in Javascript

例如,如果用户输入“ 2.5小时”或“ 65.2分钟”之类的文本,我想编写一个算法或一段代码,建议使用2.5小时,例如150分钟或150 * 60秒,等等。 。

Here a generic function that can convert to other time units with default to seconds 此处的通用函数可以转换为其他时间单位,默认为秒

function convertTo(input, to='seconds'){
  const conversionToSeconds = {'seconds':1,'minutes': 60, 'hours': 60*60}

  const [timeValue, timeUnit] = input.trim().split(/ +/);
  const timeInSeconds = timeValue * conversionToSeconds[timeUnit];
  return timeInSeconds/conversionToSeconds[to]
}

examples: 例子:

> convertTo('2.5 hours')
9000
> convertTo('2.5 hours', 'minutes')
150

It works by trimming and splitting the string on one or more spaces ('3 hours' works as well). 它通过在一个或多个空格上修剪和分割字符串来工作(“ 3小时”也是如此)。

Then the number is converted to number automatically through coercion when it is multiplied by the coefficient. 然后,将数字乘以系数,即可通过强制将数字自动转换为数字。

It first convert the number to seconds and then to the desired unit, using the same conversion map (pretty excited about this) 它首先使用相同的转换图将数字转换为秒,然后转换为所需的单位(对此感到非常兴奋)

Things that can be done better: 可以做得更好的事情:

  • do not convert when already in the right unit 在正确的单位中时不进行转换
  • convert in one step combining coefficients 一步转换系数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM