Skip to content

Instantly share code, notes, and snippets.

@RichardHyde
Last active June 21, 2020 09:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RichardHyde/3386ac57b55455b71140 to your computer and use it in GitHub Desktop.
Save RichardHyde/3386ac57b55455b71140 to your computer and use it in GitHub Desktop.
Convert a date string to a date in Applescript
-- 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
@StephanBeutel
Copy link

StephanBeutel commented Jan 30, 2018

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)

@chinwayland
Copy link

This is great.

@chinwayland
Copy link

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

@RichardHyde
Copy link
Author

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