applescript: determine the date of last Sunday
The following example AppleScript code works for me in macOS High Sierra and will return the date string of the previous Sunday:
set now to (current date)
if weekday of now is Monday then
return date string of (now - 86400)
else if weekday of now is Tuesday then
return date string of (now - 86400 * 2)
else if weekday of now is Wednesday then
return date string of (now - 86400 * 3)
else if weekday of now is Thursday then
return date string of (now - 86400 * 4)
else if weekday of now is Friday then
return date string of (now - 86400 * 5)
else if weekday of now is Saturday then
return date string of (now - 86400 * 6)
else if weekday of now is Sunday then
return date string of (now - 86400 * 7)
end if
This handler will let you pass in any date, and return back to you the date of the Sunday that came just before it. In the example below, I've applied this to the current date.
my lastSundayBefore:(current date)
--> date "Sunday, 15 December 2019 at 23h44m36"
on lastSundayBefore:(now as {date, text})
local now
if class of now = text then tell (the current date) ¬
to set [day, [its month, day, year], time, now] ¬
to [1, [word 2, word 3, word 1] of now, 0, it]
set yesterday to now - days
set today to the weekday of yesterday
set lastSunday to yesterday + (1 - today) * days
end lastSundayBefore:
The handler takes a single parameter—-the date relative to which you wish to know the previous Sunday's date—-and this can be an AppleScript date
object, or an ISO-8601 formatted string, i.e. "YYYY-MM-DD"
.
For example:
get its lastSundayBefore:"2019-10-31"
which, on my system, returns:
date "Sunday, 27 October 2019 at 00h00m00"
I saw your solution you thought didn't work, which in fact it did, and I think it is actually the best. It's simple, it's elegant, and it's easy to understand:
set theDate to the current date
repeat until (theDate's weekday) = Sunday
set theDate to theDate - 1 * days
end repeat
A recursive form of this just for fun:
on lastSundayBefore:(now as date)
local now
tell (now - days)
if its weekday = Sunday then return it
return my lastSundayBefore:it
end tell
end lastSundayBefore: