Open In App

JavaScript Program for Converting given Time to Words

Last Updated : 13 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

This article will show you how to convert the given time into words in JavaScript. The given time will be in 12-hour format (hh: mm), where 0 < hh < 12, and 0 <= mm < 60.

Examples:

Input : hh = 6, mm = 20
Output : Six Hour, Twenty Minutes
Input : hh = 8, mm = 24
Output : Eight Hour, Twenty Four Minutes

Approach:

  • First, we create an array containing words i.e. words = [One, Two, ..., Nineteen, Twenty, Thirty, Forty, Fifty].
  • To convert hours into words, we get words from the array at index hours - 1, i.e. words = [hours - 1].
  • Check if the minutes are less than 20, then get the minute words from the array at index minute - 1, i.e. words[minutes - 1].
  • If minutes are greater than or equal to 20, then we get the word at index words[(17 + Math.floor(mm / 10))] and words[(mm % 10) - 1].
  • At last, print the value on the console.

Example: Below is the implementation of the approach

JavaScript
// JavaScript Program to Convert Given Time into Words
function printWords(hh, mm) {
    let words = [
        "One", "Two", "Three", "Four", "Five",
        "Six", "Seven", "Eight", "Nine", "Ten",
        "Eleven", "Twelve", "Thirteen",
        "Fourteen", "Fifteen", "Sixteen",
        "Seventeen", "Eighteen", "Nineteen",
        "Twenty", "Thirty", "Fourty", "Fifty"
    ];

    let minutes;

    if (mm < 20) {
        minutes = words[mm - 1];
    } else {
        minutes = words[(17 + Math.floor(mm / 10))]
            + " " + words[(mm % 10) - 1];
    }

    console.log(words[hh - 1] + " Hours, "
        + minutes + " Minutes");
}

let hh = 07;
let mm = 22;
printWords(hh, mm);

Output
Seven Hours, Twenty Two Minutes

Next Article

Similar Reads