Last active
June 21, 2020 09:09
-
-
Save RichardHyde/3386ac57b55455b71140 to your computer and use it in GitHub Desktop.
Convert a date string to a date in Applescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Convert date function. Call with string in YYYY-MM-DD HH:MM:SS format (time part optional) | |
to convertDate(textDate) | |
set resultDate to the current date | |
set the month of resultDate to (1 as integer) | |
set the day of resultDate to (1 as integer) | |
set the year of resultDate to (text 1 thru 4 of textDate) | |
set the month of resultDate to (text 6 thru 7 of textDate) | |
set the day of resultDate to (text 9 thru 10 of textDate) | |
set the time of resultDate to 0 | |
if (length of textDate) > 10 then | |
set the hours of resultDate to (text 12 thru 13 of textDate) | |
set the minutes of resultDate to (text 15 thru 16 of textDate) | |
if (length of textDate) > 16 then | |
set the seconds of resultDate to (text 18 thru 19 of textDate) | |
end if | |
end if | |
return resultDate | |
end convertDate |
This is great.
So with Stephan's suggestion, the whole script would be:
-- Convert date function. Call with string in YYYY-MM-DD HH:MM:SS format (time part optional)
to convertDate(textDate)
set resultDate to the current date
set the month of resultDate to (1 as integer)
set the day of resultDate to (1 as integer)
set the year of resultDate to (text 1 thru 4 of textDate)
set the month of resultDate to (text 6 thru 7 of textDate)
set the day of resultDate to (text 9 thru 10 of textDate)
set the time of resultDate to 0
if (length of textDate) > 10 then
set the hours of resultDate to (text 12 thru 13 of textDate)
set the minutes of resultDate to (text 15 thru 16 of textDate)
if (length of textDate) > 16 then
set the seconds of resultDate to (text 18 thru 19 of textDate)
end if
end if
return resultDate
end convertDate
Thanks Stephen and Wayland, I've updated the Gist 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi,
if you try this script today or tomorrow, it will set wrong dates when you give the text (2018-02-01).
This results in setting the date to 1st of march. As febrary has only 28 days, you can't set the month to todays date. This results in a shift to march.
To always get a correct result, the script must start with this:
set resultDate to the current date
set the month of resultDate to (1 as integer)
set the day of resultDate to (1 as integer)