An AppleScript subroutine that returns the current time as hours and minutes

By Alvin J. Alexander, devdaily.com

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 current date command, so I use this method to extract the time information I want.

Without any further ado, here's the sample source code:

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

This method is instructional in several ways. First, it shows how to turn the current date into a string. Second, it demonstrates how to get a substring of a 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 strings, and how to return the merged string from the method call.

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

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

I can't take credit for writing this method -- 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.


devdaily logo