StandardIze Date Format | Pages | Find/Replace

Want to search a document and replace all instances of any date, with the same date in a standardized format. - When no year is supplied assume this year


Aug 2
August 2, 2014

Should replace all instances in document with:

Saturday, August 2, 2014

To simplify - I can format it, the question - is it possible to search text for strings that are a date?

You can get the day of the week with something like this:

set d to current date
set w to (weekday of d) as string

If I’m way off then disregard.


Short answer: no. AppleScript does not recognise dates in arbitrary formats. So you’ll have to write the code to do that - not a small thing to do.

A possibility: Apple Data Detectors can, but I do not know if they are accessible from AppleScript.
Proof of concept: I pasted your samples into a new mail message, and saved it. Placed cursor over a date, and a disclosure triangle appeared; this opened a menu with the option to go to that date in iCal. It didn’t work correctly with your 2nd sample, which is US local format - to me & my Mac it’s feb 8, not aug 2.

They are if you’re using 10.9 or later. Save the following as an ASObjC-based script library:

use framework "Foundation"

on findDatesIn:theString
	-- make a mutable string
	set theNSMutableString to current application's NSMutableString's stringWithString:theString
	-- make a date formatter with the format you want
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"EEEE, MMMM d, yyyy"
	-- create a date data detector
	set theDD to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypeDate) |error|:(missing value)
	-- find dates  in the string
	set theFinds to theDD's matchesInString:theString options:0 |range|:{location:0, |length|:length of theString}
	-- make into list and reverse order
	set theFinds to reverse of (theFinds as list)
	-- loop through
	repeat with aFind in theFinds
		-- get the date of the find
		set theDate to aFind's |date|()
		-- make a replacement date string from the date
		set newDateString to (theFormatter's stringFromDate:theDate)
		-- get the range of the date string
		set theRange to aFind's |range|()
		-- replace old date string with new
		(theNSMutableString's replaceCharactersInRange:theRange withString:newDateString)
	end repeat
	-- coerce to text and return
	return theNSMutableString as text
end findDatesIn:

And call it like this:

set theString to " Arriving 5 Jan 15 on a late plane, leaving Mar 2"
tell script "<name of lib>"
	set theResult to its findDatesIn:theString
end tell
--> " Arriving Monday, January 5, 2015 on a late plane, leaving Monday, March 2, 2015"

Shane this is great. Thank you.

BTW - Who’s not on 10.9? Anyone writing scripts I would hope is on top of OS updates :slight_smile: