Search code examples
macosfileapplescript

Applescript get last opened date of file


I can use
set modDate to the modification date of theFile as string to get the last modified date of a file, and
set modDate to the creation date of theFile as string to get the date when the file was created.

Is there anything like last opened date to get the date when the file was last opened?


Solution

  • Yes. There is a UNIX command called kMDItemLastUsedDate that returns the date the target item was last used.

    set the Last_opened_date to (do shell script "mdls -name kMDItemLastUsedDate " & quoted form of the POSIX path of theFile)
    

    However, this command doesn't return a literal date object. Instead, it returns a date object in ISO 8601:2004 format (YYYY-MM-DD HH:MM:SS) which, if you try to put date before it, you'll get a syntax error.

    Here is the revised script:

    property months : {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
    
    set the Last_opened_date to date convert_date(do shell script "mdls -name kMDItemLastUsedDate " & quoted form of the POSIX path of theFile)
    
    on convert_date(passed_data)
        set prevTIDs to AppleScript's text item delimiters
        set AppleScript's text item delimiters to space
        set the ISO_date to the first text item of (passed_data as string)
        set AppleScript's text item delimiters to "-"
        set the date_parts to every text item of the ISO_date
        set the_year to the first text item of the date_parts
        set the_month to the second text item of the date_parts
        set the_day to the third text item of the date_parts
        set AppleScript's text item delimiters to space
        set the time_string to the second text item of (passed_data as string)
        set AppleScript's text item delimiters to prevTIDs
        return item (the_month as integer) of months & the_day & ", " & the_year & space & the time_string
    end convert_date