NSDate Weirdness (and Nu!)

December 27, 2007

Now that Nu is released to the public in all its glory, I’ve been doing a lot of coding exercises in it. As is my wont, I wrote a program that prints out the current Discordian date, and in the midst of looking at the NSDate and NSCalendarDate documentation, I found this fascinating class method on NSDate:

+ dateWithNaturalLanguageString:(NSString *)string:

Creates and returns an NSDate object set to the date and time specified by a given string.

Parameters
string
A string that contains a colloquial specification of a date, such as “last Tuesday at dinner,” “3pm December 31, 2001,” “12/31/01,” or “31/12/01.”

Return Value
A new NSDate object set to the current date and time specified by string.

Discussion
This method supports only a limited set of colloquial phrases, primarily in English. It may give unexpected results, and its use is strongly discouraged.

This piqued my interest in a big way; it reminded me of the way Lotus Agenda could recognize date input such as “next Thursday” and “eight days from now”, as detailed in the fantastic book Dreaming in Code. I couldn’t just leave it alone, so I whipped up a little Nu script for you. Run it and it will present unto you a prompt, at which point I invite you to enter such phrases as:

  • next Tuesday
  • September 22, 1988
  • 3 hours from now

You will see that those phrases – and a multitude of others – are parsed correctly as NSDates, leaving you free to actually work on other things rather than futz around with NSScanners. Give it a try! And look at Nu as well!


(global readline (NuBridgedFunction functionWithName: "readline" signature: "**"))
(puts "Press Ctrl-C to quit.")
(while 1
(set input (readline ">>> "))
(set date (NSDate dateWithNaturalLanguageString: input))
(if date
(puts (date description))
(else
(puts "Your input of '#{input}' could not be parsed. Try again!"))))

Entry Filed under: cocoa, code, nu. .


About Me



I'm Patrick Thomson. I'm a sophomore at George Washington University, passionate about technology, Apple, and programming in Cocoa, Python, Ruby, and Nu.

Why "important shock"? It's an anagram of my name.

Meta

Blogroll

a

Top Posts

Blog Stats