AppleScript basic date/time format and filename I'm trying to wrap my head around AppleScript. I have a simple project to capture screenshots every several seconds and save them to a folder.

I found this helpful script on GitHub:


https://gist.github.com/jonobr1/a91c166a94a65e64c9b7


I've altered it a bit in an attempt to change the file name to this format:

screen_shot 2019-04-05 at 5.23.13 PM.jpg

Yet, I end up with a filename like this:

screen_shot0Thursday

I could use some help sorting out how to properly use the date and time functions within the script.

Here is the script:

set dFolder to "~/Desktop/screencapture/"
set theDate to current date

do shell script ("mkdir -p " &amp; dFolder)

set i to 0
repeat 960 times
    do shell script ("screencapture " &amp; dFolder &amp; "screenshot_" &amp; i &amp; theDate &amp; ".jpg")
    delay 5 -- Wait for 5 seconds.
    set i to i + 1
end repeat
If you really want to do everything in AppleScript, then you should try:

to date_format(old_date) -- Old_date is text, not a date.
    set {year:y, month:m, day:d} to date old_date
    tell (y * 10000 + m * 100 + d) as string to text 1 thru 4 &amp; "-" &amp; text 5 thru 6 &amp; "-" &amp; text 7 thru 8
end date_format

to time_format(old_time)
    set {hours:h, minutes:m, seconds:s} to date old_time
    set pre to "AM"
    if (h &gt; 12) then
        set h to (h - 12)
        set pre to "PM"
    end if
    return (h &amp; "." &amp; m &amp; "." &amp; s &amp; " " &amp; pre) as string
end time_format

set theDate to (current date)
set dateFormatted to date_format(date string of (theDate))
set timeFormatted to time_format(time string of (theDate))
set filename to  "screen_shot " &amp; dateFormatted &amp; " at " &amp; timeFormatted &amp; ".jpg"


Note: With regards to AM/PM: I haven't tried this in the evening, but it should work

It would be way easier, however to use do shell script for this, e.g.:

set formattedDate to (do shell script "date +'%Y-%m-%d at %H.%M.%S %p'")
set filename to "screen_shot " &amp; formattedDate &amp; ".jpg"


or even in one step by using: 

do shell script "screencapture \"/Users/yourusername/Desktop/screencapture/screen_shot $(date +'%Y-%m-%d at %H.%M.%S %p').jpg\" "


Make sure to replace username with your actual username, and also that the folder screencapture exists. In summary, this results in: 

set i to 0
repeat 960 times
    do shell script "screencapture \"/Users/yourusername/Desktop/screencapture/screen_shot $(date +'%Y-%m-%d at %H.%M.%S %p').jpg\" "
    delay 5 -- Wait for 5 seconds.
    set i to i + 1
end repeat


Note the importance of properly wrapping the filename in double quotes, which then needs to be escaped within AppleScript by a leading backslash: \"