Remove year from NSDateFormatterFullStyle string

2019-02-18 13:49发布

问题:

I have searched for this question and didn't find a conclusive and elegant solution. Is there anyway to change the NSDateFormatterFullStyleyear to suppress year information. I'm using the code:

    NSString *dateDescription;
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    dateDescription = [dateFormatter stringFromDate:date];
    NSLog(@"%@", dateDescription);

The result: Wednesday, March 13, 2013

Regards, Marcos

回答1:

The following is the closest you will get without lots of tricky string processing. The call to dateFormatFromTemplate:options:locale: will update the supplied template to best match the specified locale.

This assumes that the normal "Full" style gives you the weekday name, month name, and day of the month.

NSString *fullMinusYear = [NSDateFormatter dateFormatFromTemplate:@"EEEE, MMMM dd" options:0 locale:[NSLocale currentLocale]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:fullMinusYear];
NSString *dateDescription = [dateFormatter stringFromDate:date];