AppleScript time example: The current time as hours and minutes

AppleScript time subroutine FAQ: Can you share an example of an AppleScript subroutine (function) that returns te current time?

Here's an example AppleScript subroutine (also known as a function or method) that returns the current time as hours and minutes, along with the AM/PM modifier. For the purposes of creating an alarm clock AppleScript program, I didn't like the default format of the AppleScript current date command, so I use this method to extract the current time information I want.

AppleScript current time subroutine (function)

Without any further ado, here's my AppleScript current time example code (AppleScript subroutine):

on getTimeInHoursAndMinutes()
  -- Get the "hour"
  set timeStr to time string of (current date)
  set Pos to offset of ":" in timeStr
  set theHour to characters 1 thru (Pos - 1) of timeStr as string
  set timeStr to characters (Pos + 1) through end of timeStr as string

  -- Get the "minute"
  set Pos to offset of ":" in timeStr
  set theMin to characters 1 thru (Pos - 1) of timeStr as string
  set timeStr to characters (Pos + 1) through end of timeStr as string

  --Get "AM or PM"
  set Pos to offset of " " in timeStr
  set theSfx to characters (Pos + 1) through end of timeStr as string

  return (theHour & ":" & theMin & " " & theSfx) as string
end getTimeInHoursAndMinutes

Discussion

I think this AppleScript subroutine is instructional in several ways. First, it shows how to turn the AppleScript current date into an AppleScript string. Second, it demonstrates how to get a substring of an AppleScript string, using the position of the ":" and " " characters to determine where the substrings should begin and end. Finally, it also shows how to merge several AppleScript strings, and how to return the merged string from the AppleScript subroutine call.

In my AppleScript alarm clock program I call this AppleScript subroutine using the AppleScript say command, like this:

say "The current time is " & getTimeInHoursAndMinutes() using "Trinoids" 

Summary

I can't take all the credit for writing this AppleScript current time subroutine -- certainly not all of it -- but I also can't find the source code I originally adapted this from. So, many thanks to the original author, and I hope I've added some improvements to it.