AppleScript Date format and calculation
Question 1: Rather than going through the trouble of obtaining the current date
only to convert it to another format, you can obtain it in the right format straight away with a bash command:
do shell script "date +'%m/%d/%Y'"
--> 03/24/2018
Question 2: First, reformat the date into that which your system can recognise. In your case (and mine), it's dd/mm/yyyy
:
set [M, ordinal, Y] to the words of "June 2nd, 2012"
set the text item delimiters to {"st", "nd", "rd", "th"}
set cardinal to (first text item of ordinal) --> "2"
set cardinal to text -1 thru -2 of ("0" & cardinal) --> "02"
set the text item delimiters to space
set date_string to {M, cardinal, Y} as text
-- date -j -f '%B %d %Y' 'June 02 2012' +'%d/%m/%Y'
set command to {¬
"date -j -f '%B %d %Y'", ¬
quoted form of the date_string, ¬
"+'%d/%m/%Y'"}
do shell script (command as text) --> "02/06/2012"
Then subtract one date from the current date, and divide by days
to get the number of days between the two dates:
((current date) - (date result)) / days
--> 2121.627
PS. You can use that same shell command to convert the date into your first format, mm/dd/yyyy
, simply by switching %d
and %m
at the end of the command
string.
ADDENDUM:
I thought I'd also show you how to convert the third date string into your desired format using pure AppleScript. It can be done rather quite elegantly, actually:
set today to "Saturday 24 March 2018"
set [_day, _month, _year] to [day, month, year] of date today
--> {24, March, 2018}
set _month to _month * 1 --> 3
set _month to text -1 thru -2 of ("0" & _month) --> "03"
set the text item delimiters to "/"
return {_month, _day, _year} as string
--> "03/24/2018"
Note to other users: The code in this addendum may or may not work for you, depending on your system settings. AppleScript is notoriously fussy about what it will and will not recognise as a date string. The OP and I appear to have similar or identical Language & Region date settings, which allows the variable today
to be interpreted correctly as a date by AppleScript, whilst the same code running on a different system would throw an error.
To adapt the code here for use on your own system, first run the command get date string of (current date)
to get a preview of the date format used by your system, then change the variable declaration for today
to match. Alternatively, set the variable today
to the date string of (current date)
.