In AppleScript if you have a string with a date and try to convert it to a class of date
it will error out in Finder and System Events. Example:
set testDate to "Friday, September 21, 2018 at 6:54:29 PM"
set testResult to date testDate
return testResult
renders:
When placing the above code in a System Event:
tell application "System Events"
set testDate to "Friday, September 21, 2018 at 6:54:29 PM"
set testResut to date testDate
return testResut
end tell
returns:
System Events got an error: Can’t get date "Friday, September 21, 2018
at 6:54:29 PM".
Trying to place the above in a Finder tell:
tell application "Finder"
set testDate to "Friday, September 21, 2018 at 6:54:29 PM"
set testResut to date testDate
return testResut
end tell
Finder got an error: Can’t get date "Friday, September 21, 2018 at
6:54:29 PM".
What should I use to be able to convert a date string to an actual date if I'm already using either System Events or Finder? The only alternative I've found is to create a handler:
tell application "System Events"
set testDate to "Friday, September 21, 2018 at 6:54:29 PM"
return my stringDate(testDate)
end tell
on stringDate(theString)
set attempt to date theString
return attempt
end stringDate
How can I do a date
conversion in a System Event or Finder tell block?
There's been discussion in comments with the supplied answer but given the system specs of:
macOS High Sierra version 10.13.6
and copied solution:
tell application "System Events"
set testDate to "Friday, 21 September, 2018 at 6:54:29 PM"
set testResult to my (date testDate)
end tell
Opened a new Script Editor:
Pasted code solution:
Compiled code solution:
Ran code solution:
Issue still persists.
Best Answer
That's interesting, I had never noticed this oddity of AppleScript before. Strangely, if you create the
date
object using a string by value, neither System Events nor Finder has a problem:is absolute fine (the format of my date string is different to yours, as per my system settings).
It's only when referencing the string's value using a variable that the issue presents itself:
as you pointed out, is not allowed.
Solution:
It turns out the solution is to refer the job to the top-level AppleScript object using
my
(orAppleScript's
):Note to other users: AppleScript date strings are formatted according to your system's date/time settings, therefore a direct copy-n-paste of any of the above snippets—either mine or the OP's—may still generate an error. You need to determine the appropriate format to use for the date string on your system, which is most easily done by examining the value returned by the AppleScript command
current date
, and using that as a template.