Add AM PM suffix to an hour
Turn an hour from 0 to 23 into a 12-hour label with am or pm.
function suffixAmPm(hour) { return `${hour % 12 === 0 ? 12 : hour % 12}${hour < 12 ? 'am' : 'pm'}`; }
Input & expected output
Input
15Expected output
"3pm"The edge case
Input
0Expected output
"12am"Know the limits
- Input is an integer hour from 0 to 23.
- For text a reader sees, prefer Intl.DateTimeFormat in the reader’s locale.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Add AM PM suffix to an hour from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Original implementation kept; integer 0–23 validation and locale note. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Compare two dates — Compare validated ISO calendar dates in UTC and return -1, 0 or 1.
- Calculate the number of days between two dates — Count whole calendar days between two YYYY-MM-DD dates.
- Convert a date to YYYY-MM-DD format — Format an ISO date-time as its UTC calendar date.