Skip to content

Time Formatting

image Source: adopted from here

Introduction

Time can be expressed in different formats. Below are a few examples:

Format Example Description
HH:MM:SS 14:24:52 The time is based on a 24 hour system
HH:MM:SS XM 02:24:52 PM The time is based on a 12 hour system. AM or PM is given

Question

Write a function formatTime to format a time into 12 hour clock format. For example,

formatTime[01:58:57] / "01:58:57 AM"
formatTime[14:34:45] / "02:34:45 PM"

Answer

A boolean value can be used to select from binary values.

formatTime:{
  cutoff:12:00:00;
  if[x=cutoff;:"12:00:00 PM"];
  i:x>cutoff;
  string[x-cutoff*i]," ","AP"[i],"M"
  };