Neha M
Neha M

Reputation: 463

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

For e.g., if a user types in a text like '2.5 hours' or '65.2 minutes', I want to write an algorithm or piece of code that will suggest for 2.5 hours, things like 150 minutes or 150 * 60 seconds, so on.

Upvotes: 0

Views: 67

Answers (1)

Francesco
Francesco

Reputation: 4250

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).

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

Upvotes: 3

Related Questions