DEV Community

dev.to staff
dev.to staff

Posted on

Daily Challenge #290 - Read the Time

Given time in 24-hour format, convert it to words.

For example:
13:00 = one o'clock 
13:09 = nine minutes past one 
13:15 = quarter past one 
13:29 = twenty nine minutes past one
13:30 = half past one 
13:31 = twenty nine minutes to two
13:45 = quarter to two 
00:48 = twelve minutes to one
00:08 = eight minutes past midnight
12:00 = twelve o'clock
00:00 = midnight

Note: If minutes == 0, use 'o'clock'. If minutes <= 30, use 'past', and for minutes > 30, use 'to'. 

Good luck!

Tests:

07:01
01:59
12:01
00:01
11:31
23:31


This challenge comes from KenKamau on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Top comments (1)

Collapse
 
soorajsnblaze333 profile image
Sooraj (PS)
const digits = ['midnight','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty '];
const keys = ["o'clock", "quarter", "half"]

const timeToWord = (time) => {
  let num = time.split(':').map((t, i) => (i === 0 && t !== '12') ? +t % 12 : +t);
  let word = '';
  if (!num[0] && !num[1]) word = digits[0];
  else if(num[0] && !num[1]) word = digits[num[0]] + " " + keys[0];
  else {
    if (num[1] <= 30) {
      if (num[1] % 15 === 0) word = keys[num[1] / 15] + " past " +  digits[num[0]]; 
      else word = (num[1] > 20 ? (digits[20] + digits[num[1] - 20]) : digits[num[1]]) + (num[1] > 1 ? " minutes " : " minute ") + "past " + digits[num[0]];
    } else {
      num[1] = 60 - num[1];
      num[0] += 1;
      if (num[0] === 12) num[0] = (+time.split(':')[0] > 12 ? 0 : 12)
      if (num[1] % 15 === 0) word = keys[num[1] / 15] + " to " +  digits[num[0]]; 
      else word = (num[1] > 20 ? (digits[20] + digits[num[1] - 20]) : digits[num[1]]) + (num[1] > 1 ? " minutes " : " minute ") + "to " + digits[num[0]];
    }
  }
  console.log(time + " = " + word);
  return word;
}

timeToWord('13:00');
timeToWord('13:09');
timeToWord('13:15');
timeToWord('13:29');
timeToWord('13:30');
timeToWord('13:31');
timeToWord('13:45');
timeToWord('00:48');
timeToWord('00:08');
timeToWord('12:00');
timeToWord('00:00');

timeToWord('07:01');
timeToWord('01:59');
timeToWord('12:01');
timeToWord('00:01');
timeToWord('11:31');
timeToWord('23:31');

A little big but does the job

Output
Output