AppleScript basic date/time format and filename

applescriptautomatorscreen capture

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:

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 " & dFolder)

set i to 0
repeat 960 times
    do shell script ("screencapture " & dFolder & "screenshot_" & i & theDate & ".jpg")
    delay 5 -- Wait for 5 seconds.
    set i to i + 1
end repeat

Best Answer

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 & "-" & text 5 thru 6 & "-" & 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 > 12) then
        set h to (h - 12)
        set pre to "PM"
    end if
    return (h & "." & m & "." & s & " " & 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 " & dateFormatted & " at " & timeFormatted & ".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 " & formattedDate & ".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: \"