And one of the nice things about script libraries is that you can hide it away. And interleaved syntax can help define more descriptive handler names.
use framework "Foundation"
on formatDate:theDate usingFormat:formatString
if class of theDate is date then set theDate to my makeNSDateFrom:theDate
set theFormatter to current application's NSDateFormatter's new()
theFormatter's setDateFormat:formatString
set theString to theFormatter's stringFromDate:theDate
return theString as text
end formatDate:usingFormat:
on makeNSDateFrom:theASDate
set {theYear, theMonth, theDay, theSeconds} to theASDate's {year, month, day, time}
if theYear < 0 then
set theYear to -theYear
set theEra to 0
else
set theEra to 1
end if
set theCalendar to current application's NSCalendar's currentCalendar()
set newDate to theCalendar's dateWithEra:theEra |year|:theYear |month|:(theMonth as integer) ¬
|day|:theDay hour:0 minute:0 |second|:theSeconds nanosecond:0
return newDate
end makeNSDateFrom:
Called by:use theLib : script "<name of lib>"
use scripting additions
theLib's formatDate:(current date) usingFormat:"ddMMMYY"
--> "20Jan14"
theLib's formatDate:(current date) usingFormat:"dd MMMM YY"
--> "20 January 14"