Datepicker issue: format date to "mm/dd/yyyy"

All,
I have datepickers in my app and I need to format their value to “mm/dd/yyyy” format.
Currently I get the output in following form:
Sunday, January 1, 2012 8:00:00 AM Pacific Standard Time

Here the code:

script AppDelegate
property aStartDate : missing value # Linked in IB
property aEndDate : missing value # Linked in IB

on submitForm()
set stdate to aStartDate's stringValue() as string
set enddate to aEndDate's stringValue() as string

display dialog stdate # Sunday, January 1, 2012 8:00:00 AM Pacific Standard Time

end submitForm
end script

Is there an easier way to format the date?

Got it. Found the solution in the forums


        set stdate to aStartDate's dateValue()
        set theCal to current application's class "NSCalendar"'s currentCalendar()
        set theComponents to theCal's components_fromDate_(254, stdate)
        set theYear to theComponents's |year|() as string
        set theMonth to theComponents's |month|() as string
        set theDay to theComponents's |day|() as string
        display dialog (theMonth & "/" & theDay & "/" & theYear)

You can also use a date formatter:

set stdate to current application's NSDate's |date|()
set df to current application's NSDateFormatter's alloc()'s init()
df's setDateFormat_("mm/dd/yyyy")
return df's stringFromDate_(stdate)

or

set stdate to current application's NSDate's |date|()
return stdate's descriptionWithCalendarFormat_timeZone_locale_("%m/%d/%Y", missing value, missing value)

thanks guys…

To obtain a compact version of the date, use short date string. For example, short date string
of (current date) --result: “1/27/08”.

There are two problems with that in this case, though: first, the user wants the year as yyyy, not yy, and second, he’s starting off with an NSDate, not an AS date, so short date string isn’t applicable.

Yep, although the docs say: “You are strongly encouraged to migrate to using v10.4 behaviour” and “There are several problems with the implementation of this method that cannot be fixed for compatibility reasons. To format a date, you should use a date formatter object instead.”

@shane: I tried using a date formatter.


set theNSDate to aStdate's dateValue() 
set df to current application's NSDateFormatter's alloc()'s init()
df's setDateFormat_("mm/dd/yyyy")
set mystdate to  df's stringFromDate_(theNSDate)
log mystdate

I got the following output
00/03/2012

I always get 00 for the month. What did I miss?

Looks like it needs to be “MM/dd/yyyy”. This worked for me

Yep – lowercase m is minutes.