Search code examples
cocoansdatepicker

Cocoa Date Picker formatting


This prints the selected datePicker's date to a textField like this:

February 9, 2012 ...

NSDate *theDate = [calendar dateValue];
if (theDate)
{
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];

    NSString *formattedDateString;

    [formatter setDateStyle:NSDateFormatterLongStyle];
    [formatter setTimeStyle:NSDateFormatterNoStyle];
    formattedDateString = [formatter stringFromDate:theDate];
    [dateString setStringValue: formattedDateString];

 }

}

How do I format the printed string to look like this?

2012-02-09

I tried adding a dateFormatter to the textField and customizing how it should display a date. Doesn't work.

Thanks for the help.


Solution

  • You can do it like this:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *theDate = [calendar dateValue];
    
    NSString *formatedDateString = [formatter stringFromDate:theDate];
    
    [formatter release];