-
-
Save darrenpmeyer/87beea84082bebad6296 to your computer and use it in GitHub Desktop.
-- convert an AppleScript Date object to a POSIX date CCYYMMDDHHmm.SS | |
on posixDate(datetime) | |
-- date -j -f "%A, %B %e, %Y at %I:%M:%S %p" "Tuesday, September 1, 2015 at 11:00:00 AM" +%Y%m%d%H%M | |
set command to "date -j -f '%A, %B %e, %Y at %I:%M:%S %p' '" & datetime & "'" | |
set command to command & " +%Y%m%d%H%M.%S" | |
set thePosixDate to do shell script command | |
return thePosixDate | |
end posixDate | |
-- convert an AppleScript Date object to a UNIX timestamp (seconds since epoch) | |
on unixDate(datetime) | |
set command to "date -j -f '%A, %B %e, %Y at %I:%M:%S %p' '" & datetime & "'" | |
set command to command & " +%s" | |
set theUnixDate to do shell script command | |
return theUnixDate | |
end unixDate |
@darrenpmeyer, thanks for sharing a great set of functions.
I was hoping to use your posixDate() function as a general purpose date formatting function. I changed your arguments to add a "formatCodes" parameter, and replaced your
set command to command & " +%Y%m%d%H%M.%S"
with
set command to command & " +" & formatCodes
It seems to work find, but ignores any codes after a space.
So "%Y-%m-%d"
works fine.
But "%Y-%m-%d" %H:%M:%S"
does not. The hours, min, and sec are not returned.
Here the complete function with my changes:
set dDate to current date
set strDate1 to formatDate(dDate, "%Y-%m-%d")
set strDate2 to formatDate(dDate, "%Y-%m-%d %H:%M:%S")
set strDate3 to formatDate(dDate, "%Y-%m-%d-%H:%M:%S")
log strDate1
log strDate2
log strDate3
on formatDate(pDate, pstrFormat)
-- convert an AppleScript Date object to a POSIX date
set command to "date -j -f '%A, %B %e, %Y at %I:%M:%S %p' '" & pDate & "'"
set command to command & " +" & pstrFormat
set thePosixDate to do shell script command
return thePosixDate
end formatDate
this returns:
(*2015-12-26*)
(*2015-12-26*)
(*2015-12-26-05:09:42*)
Have I done something wrong?
Thanks again for sharing, and for your help.
You need to surround the format string with single-quotes or the shell will see multiple arguments. So do:
set command to "date -j -f '%A, %B %e, %Y at %I:%M:%S %p' '" & pDate & "'"
set command to command & " +'" & pstrFormat & "'"
Thanks.
How can we convert unix time to AppleScript date object?
Nice. They've had posix paths forever... just never posix dates.