Converting 24-Hour to 12-Hour Time

JavaScript provides the time in 24-hour format, also known as military time. Many people are unfamiliar or uncomfortable with this format, so you’ll want to know how to convert it to 12-hour format. In the next two scripts, you see one way to go about the task, which needs a bit of explanation. Our page (Script 12.6) has two important elements: an h2 tag and a form. The script will write the time into the former. The latter contains two radio buttons, which let us switch the time from 24-hour format into 12-hour format. The JavaScript behind this is in Script 12.7. The result is shown in Figure 12.5.

Figure 12.5. The script in action.

Script 12.6. This HTML uses ids to identify each radio button.
<!DOCTYPE ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.