Horje
JavaScript Program for Converting given Time to Words

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



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers
JavaScript Program to Remove First and Last Characters from a String JavaScript Program to Remove First and Last Characters from a String
JavaScript Program to Find Second Largest Element in an Array JavaScript Program to Find Second Largest Element in an Array
JavaScript Program to Find Next Smaller Element JavaScript Program to Find Next Smaller Element
Opposite Words in English: A to Z List, For Class 1 to Class 3 Opposite Words in English: A to Z List, For Class 1 to Class 3

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
8