Get meridiem suffix of integer

OSCC · JavaScript, Date · Oct 19, 2020

Converts an integer to a suffixed string, adding am or pm based on its value.

  • Use the modulo operator (%) and conditional checks to transform an integer to a stringified 12-hour format with meridiem suffix.
const getMeridiemSuffixOfInteger = num =>
  num === 0 || num === 24
    ? 12 + 'am'
    : num === 12
    ? 12 + 'pm'
    : num < 12
    ? (num % 12) + 'am'
    : (num % 12) + 'pm';
getMeridiemSuffixOfInteger(0); // '12am'
getMeridiemSuffixOfInteger(11); // '11am'
getMeridiemSuffixOfInteger(13); // '1pm'
getMeridiemSuffixOfInteger(25); // '1pm'

Recommended snippets

  • Format duration

    JavaScript, Date

    Returns the human-readable format of the given number of milliseconds.

  • Converts a date to extended ISO format (ISO 8601), including timezone offset.

  • Add minutes to date

    JavaScript, Date

    Calculates the date of n minutes from the given date, returning its string representation.