AppleScript: How to get time without seconds? Alternatively, how to remove text in middle of string?

If you use the following code:

set CurrentTime to (time string of (current date))

The CurrentTime will be set in the following format:

12:02:38 PM

However, I want CurrentTime to be:

12:02 PM

So, I want to remove the characters in the 6, 7, and 8 positions in the string.

How can this be accomplished in AppleScript? Thank you.


You can use something like this:

set CurrentTime to (do shell script "date +\"%l:%M %p\" | awk '{$1=$1;print}'")

There's more info about date and its modifiers at cyberciti.

%l - hour (1..12)
%M - minute (00..59)
%p - locale’s equivalent of either AM or PM; blank if not known

Here is an AppleScript subroutine I found doing a Google search that does what you asked.

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

set CurrentTime to getTimeInHoursAndMinutes()

One AppleScript-only option is:

# your line
set CurrentTime to (time string of (current date))
# place all the words of the time string into a list
set EveryWord to every word of CurrentTime
# do a very basic test on what we got and assemble the string using the parts plus separators
if length of EveryWord = 4 then
    # if we have 4 words, there must be a form of AM/PM
    set CurrentTime to item 1 of EveryWord & ":" & item 2 of EveryWord & " " & item 4 of EveryWord
else
    # 24-hour clock
    set CurrentTime to item 1 of EveryWord & ":" & item 2 of EveryWord
end if