Reputation: 227
I am trying to read a time / date variable from a .txt
file using an apple script.
Depending on the time / date in the file I want to stop the apple script or run the rest of the apple script.
So the .txt
file lives on my desktop so my apple script is as below:
set desktop_folder to "$HOME/Desktop"
set myFile to "timeDate.txt"
do shell script "echo my file contents is:" & myFile
if myFile < 2021-09-25 then
error number -128
end if
The date in timeDate.txt
file is less 2021-09-25
so it should stop the rest of the code from running. I can't see why the code doesn't stop.
Upvotes: 0
Views: 268
Reputation: 1878
To compare string dates without localization issues for a specific user, they should first be converted to date objects:
-- script: example for comparing string dates
-- assuming the content of text file is a single entry,
-- in the same format as e.g. "2021-09-25"
set comparedDateString to "2021-09-25"
set readDateString to read (choose file of type "txt")
set dateObject to (current date)
set dateObject's year to (text 1 thru 4 of comparedDateString) as integer
set dateObject's day to (text 9 thru 10 of comparedDateString) as integer
set dateObject's month to (text 6 thru 7 of comparedDateString) as integer
set comparedDate to dateObject
set dateObject's year to (text 1 thru 4 of readDateString) as integer
set dateObject's day to (text 9 thru 10 of readDateString) as integer
set dateObject's month to (text 6 thru 7 of readDateString) as integer
set readDate to dateObject
if readDate < comparedDate then error number -128
Upvotes: 1
Reputation: 7555
Assuming the content of timeDate.txt is a single entry in the same format as e.g. 2021-09-25
without a trailing linefeed, then the following example AppleScript code does what you are attempting to do.
Example AppleScript code:
set myFile to POSIX path of ¬
(path to desktop) & "timeDate.txt"
set dateString to read myFile
if dateString < "2021-09-25" then return
If you run into a issue comparing a date
as text/string, then use:
Example AppleScript code:
set thisDate to "2021-09-25"
set myFile to POSIX path of ¬
(path to desktop) & "timeDate.txt"
set dateString to read myFile
if date dateString < date thisDate then return
Upvotes: 0