Jake.codes

Last Calendar Event, for OS X

Friday, February 14, 2014

I attempted this challenge with and without the incredibly useful tool icalBuddy. You can install it with Homebrew pretty simply: brew install icalbuddy

With icalBuddy

-- Set your calendar name:
set myCalendar to "Home"

on getMostRecentEvent()
    set myEventUID to do shell script ("/usr/local/bin/icalBuddy -uid -b '' -eep 'title,datetime,url,location,notes,attendees,priority' -npn -ic '" & myCalendar & "' eventsFrom:'last year' to:'now' | tail -n 1")
    tell application "Calendar"
        tell calendar myCalendar
            return every event whose uid is equal to myEventUID
        end tell
    end tell
end getMostRecentEvent

getMostRecentEvent()

Without icalBuddy

tell application "Calendar"
    set today to (current date)
    set myEvents to every event of calendar "Home"
    set myMostRecentEvent to ""
    set myMostRecentEventDateDifference to ""
    
    repeat with theEvent in myEvents
        set theEndDate to end date of theEvent
        set theEventDateDifference to (today - theEndDate)
        
        if today - theEndDate > 0 then
            if myMostRecentEvent is not "" then
                if (myMostRecentEventDateDifference) > (theEventDateDifference) then
                    set myMostRecentEvent to theEvent
                    set myMostRecentEventDateDifference to theEventDateDifference
                end if
            else
                set myMostRecentEvent to theEvent
                set myMostRecentEventDateDifference to theEventDateDifference
            end if
        end if
        
    end repeat
    
    return summary of myMostRecentEvent & " on " & end date of myMostRecentEvent as text
end tell