iOS Date Format conversion

496 views Asked by At

I have the following routine which will return a date & time string, and is called from another routine. This part works fine.

- (NSDate * )startDateOfToday
 {
   NSCalendar *calendar = [NSCalendar currentCalendar];
   NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                           fromDate:[NSDate date]];
   return [calendar dateFromComponents:components];
 }

However, whilst in the calling code, which needs the date string as provided, I need to generate a different view of the date that I can pass to a label similar to this:-

self.dayLabel.text = [?????????];

And want the date to show as 'Sat, Dec 7' or whatever date the code is returning.

As I understand it, I need to use NSDateFormatter to convert the date string provided by startDateOfToday to a new value of 'Sat, Dec 7'.

I appreciate there are numerous posts relating to DateFormat, but am struggling to understand how to do this.

Could someone help me with:- a) the code to convert b) the code to go in place of the ???? on the dayLabel, as whenever I try things, it often shows a conversion error etc.

Thank you.

1

There are 1 answers

1
thorb65 On BEST ANSWER

try this:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
[dateFormatter setDateFormat:@"EEE, MMM d"];

self.dayLabel.text = [dateFormatter stringFromDate:yourDate];
// or self.dayLabel.text = [dateFormatter stringFromDate:[self startDateOfToday]];