Get Meridiem Suffix of Integer

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to convert an integer to a suffixed string with a meridiem suffix in JavaScript. We will use the modulo operator and conditional checks to transform the integer into a 12-hour format with either 'am' or 'pm' added based on its value. This lab will provide a practical exercise in handling time values in JavaScript.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/BasicConceptsGroup -.-> javascript/str_manip("`String Manipulation`") subgraph Lab Skills javascript/variables -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} javascript/data_types -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} javascript/arith_ops -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} javascript/comp_ops -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} javascript/cond_stmts -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} javascript/str_manip -.-> lab-28355{{"`Get Meridiem Suffix of Integer`"}} end

How to Get the Meridiem Suffix of an Integer

To get started with coding, open the Terminal/SSH and type node.

Here's a function that converts an integer to a 12-hour format string with a meridiem suffix.

To do this, use the modulo operator (%) and conditional checks.

const getMeridiemSuffixOfInteger = (num) => {
  if (num === 0 || num === 24) {
    return "12am";
  } else if (num === 12) {
    return "12pm";
  } else if (num < 12) {
    return num + "am";
  } else {
    return (num % 12) + "pm";
  }
};

Here are some examples of how to use this function:

getMeridiemSuffixOfInteger(0); // '12am'
getMeridiemSuffixOfInteger(11); // '11am'
getMeridiemSuffixOfInteger(13); // '1pm'
getMeridiemSuffixOfInteger(25); // '1pm'

This function takes an integer as an argument and returns a string with the meridiem suffix.

Summary

Congratulations! You have completed the Get Meridiem Suffix of Integer lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like