Many people want to process dates, e.g., for use in a filename. However, the correct format is often colloquial and up for debate.
Here is a little pure AppleScript routine that may be useful for producing a date in the desired format…
set theDateString to my createDate((current date)) -- Call the handler to create your date string
--> "2022-12-09"
-- Do stuff here, whatever your script calls for
-- Handlers
on createDate(theDate) -- Process Date
set {year:y, day:d, month:m} to theDate -- Set variables for each date component
set od to AppleScript's text item delimiters -- Cache the default text delimiters
set AppleScript's text item delimiters to "-" -- Switch the delimiters to the desired value
set dateString to {y, my zeropad(d), my zeropad(m as integer)} as string -- Create a string from the date components, zeropadded. Reorder the components, as desired.
set AppleScript's text item delimiters to od -- Reset the text item delimiters
return dateString -- Pass the date string back to the script
end createDate
on zeropad(num) -- Add prefixing zero
if num ≥ 10 then
return num
else
return ("0" & num as string)
end if
end zeropad
As I personally prefer as few lines as possible (makes it easier to few more code on the screen), I couldn’t resist to do a shorter version of your script:
on createDate(theDate) -- Process Date
return (year of theDate as string) & "-" & my zeropad(day of theDate) & "-" & my zeropad(month of theDate as integer)
end createDate
on zeropad(num) -- Add prefixing zero
if num ≥ 10 then return (num as string)
return ("0" & num as string)
end zeropad
And soon @chrillek will probably provide an even shorter JavaScript revision
Taking the bait (but without any warranty since I’m away from my Mac). Unfortunately, it’s a no-brainer.
function createDate(date) {
return date.toISOString();
}
This will convert a date to its ISO representation, including the time. If the time is not needed, the caller should remove everything after and including the „T“ in the string.
Weirdly this seems to be something that’s way easier in Shortcuts. There’s a built-in action “Format” which takes a format string. I just used it to set up a shortcut to add a new journal entry in Markdown to my journal entries folder.
Yes, but there are just many other problems and inadequacies with Shortcuts
PS: You also learn nothing from it. The point of my post is a learning opportunity for those interested in scripting and dealing with a common inquiry.
I use the date functions on both a Mac (Applescript) and iPad (Shortcuts)
Not seeing the “weirdly…way easier”; both require a level of skill with the product
I’m aware that Shortcuts can be used on a Mac, but find it too limited for my use
I just used it to set up a shortcut to add a new journal entry in Markdown to my journal entries folder.
I use the shortcut with iPad shortcut to create DT notes, pre-coded with a filename date prefix
On the Mac, it’s an Applescript
I prefer formatted note (html) notes