Can't set date using a variable

I found a solution before posting but I thought I’d ask anyway why this “date” syntax does not work within Calendar. After wasting a bit of time under the assumption that the date function should always work within Calendar, I dispiritedly tried pasting it outside the Calendar Tell and WTF?, it worked.

Why does this work within Calendar, with a literal string?:


	set theDate to date "Friday, June 16, 2017 at 12:00:00 AM"
	return theDate

but not when using a variable, like this?:


	set theDateStr to "Friday, June 16, 2017 at 12:00:00 AM"
	set theDate to date theDateStr
	return theDate

It works outside Calendar. Any thoughts?

Model: MacBook Pro
AppleScript: 2.5
Browser: Safari 602.4.8
Operating System: Mac OS X (10.10)

I can’t test your code because you use an “English” date when I use “french” ones.
As you didn’t gave the error message which you got I may just give two tracks :

 set theDateStr to "Friday, June 16, 2017 at 12:00:00 AM"
  tell me to set theDate to date theDateStr # EDITED
   return theDate

or, probably better:

# replace the original code by:
set theDate to my stringToDate("Friday, June 16, 2017 at 12:00:00 AM")

# At the very end of the script - out of the code dedicated to Calendar - paste this handler
on stringToDate(theDateStr)
	set theDate to date theDateStr
	return theDate
end stringToDate

Yvan KOENIG running Sierra 10.12.4 in French (VALLAURIS, France) mardi 4 avril 2017 21:00:07

Things like that can happen sometimes with AppleScript. When you write .

set theDate to date "Friday, June 16, 2017 at 12:00:00 AM"

. the date specifier (ie. class + string) is there in the script code and the compiler compiles it into a date object. When you use a variable with ‘date’ in front of it, the specifier’s not resolved until the script runs. So in a ‘tell’ statement to another application, it’s effectively that application which is being told to turn the specifier into a date object, which it may not know how to do, even though it can use the date object once it exists. The trick, as you’ve discovered, is to resolve date specifiers in the context of the script itself.

Thanks Nigel! That helps.