On Aug 20, 2015, at 11:13 AM, Stockly, Ed <email@hidden> wrote:
I used to be able to do this:
Date "September 4" Date "Fri., September 4" Date "Fri. Sept. 4"
At the risk of flogging a dead horse, I should point out that there is an alternative API for *guessing* dates from strings. It's data detectors, a technology resurrected from OSes of old, and it's what used when, for example, you hover over a date in an email or document. It actually searches through a string for potential dates, rather than treating the whole string as a single date. It does a sort of enhanced regular-_expression_ search based on your locale.
So as an exercise, let's throw a variation of the above at it (and I've set my date format to US for this):
use framework "Foundation" use script "BridgePlus" on getDatesIn:aString set anNSString to current application's NSString's stringWithString:aString set {theDetector, theError} to current application's NSDataDetector's dataDetectorWithTypes:(current application's NSTextCheckingTypeDate) |error|:(reference) set theMatches to theDetector's matchesInString:anNSString options:0 range:{0, anNSString's |length|()} set theDates to current application's NSMutableArray's array() repeat with i from 1 to theMatches's |count|() set thisMatch to (theMatches's objectAtIndex:(i - 1)) (theDates's addObject:(thisMatch's |date|())) end repeat return theDates end getDatesIn:
set theString to "Sunny September 4 Fri., September 1 Fri. Sept. 2 Fri Sep 3 Sep. 4 Sept. 9 9/8 9/7/15 09/06/2015 9/5/2015" set theDates to ASify from (my getDatesIn:theString) --> { date "Friday, September 4, 2015 at 12:00:00 PM", date "Tuesday, September 1, 2015 at 12:00:00 PM", date "Wednesday, September 2, 2015 at 12:00:00 PM", date "Thursday, September 3, 2015 at 12:00:00 PM", date "Friday, September 4, 2015 at 12:00:00 PM", date "Wednesday, September 9, 2015 at 12:00:00 PM", date "Monday, September 7, 2015 at 12:00:00 PM", date "Sunday, September 6, 2015 at 12:00:00 PM", date "Saturday, September 5, 2015 at 12:00:00 PM" }
As you can see, it picked up all but the m/d form -- because it's parsing the complete string, it presumably errs on the side of caution given that #/# might be a fraction.
Now that might well be good enough for your use: you could prompt only if it failed, or do an initial count of slashes. It depends on what's acceptable to you.
But if you run it with the string that started this thread:
set theDates to ASify from (my getDatesIn:"10:11") --> { date "Friday, August 21, 2015 at 10:11:00 PM" }
You will see that, for some unknown reason, it guessed wrong. That's probably worth logging as a bug, but the point is that unless the format of the string and the expected format of the string match, it's just guesswork. Educated guesswork, for sure -- but as you can see, not infallible.
(Oh, and data detectors are very neat, and aren't limited to dates...)
|