Search code examples
iosobjective-cnsdateformatteruidatepicker

I want month in three alphabet format but MMM is returning month number with "M" at beginning in iOS UIDatePicker


This is my method which gets executed when UIDatePicker time is selected:

-(void) datePickerAction: (UIDatePicker *)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[NSLocale systemLocale]];
    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss zzzz yyyy"];
    self.dateTextView.text = [dateFormatter stringFromDate:self.datePicker.date];
}

This gives me date as Tue M09 29 10:26:29 GMT+05:30 2015

I want my month to appear in three alphabet format like OCT or JAN. Surprisingly, if i comment line [dateFormatter setLocale:[NSLocale systemLocale]]; then i get month in correct way as Tue Sep 29 10:26:29 Indian Standard Time 2015 with same date formatter. Please tell me where I am going wrong.

My desired date format example is Tue Sep 29 10:26:29 GMT+05:30 2015


Solution

  • I got little idea on the root cause of my problem after reading to Amin Negm-Awad's answer. So, I implemented a work around and it is working perfectly fine in my situation. For getting my date in my desired format, I decided to use two NSDateFormatter with different locale and then I appended string from both the formatter to get desired results.

    For getting month in three letter month, I made a NSDateFormatter object and set it's locale as [NSLocale currentLocale] this gave me month name in three letter format.

    For getting GMT, I made another NSDateFormtter object and set it's locale as [NSLocale systemLocale] and this gave me GMT format.

    After this, I appended both the strings and I got desired results. Complete modified code given below:

    -(void) datePickerAction: (UIDatePicker *)sender {
        [self.datePicker setLocale:[NSLocale currentLocale]];
    
        NSDateFormatter *dayMonthDate = [NSDateFormatter new];
        [dayMonthDate setLocale:[NSLocale currentLocale]];
        [dayMonthDate setDateFormat:@"EEE MMM dd HH:mm:ss"];
    
        NSDateFormatter *gmtAndYearFormatter = [NSDateFormatter new];
        [gmtAndYearFormatter setLocale:[NSLocale systemLocale]];
        [gmtAndYearFormatter setDateFormat:@"zzzz yyyy"];
    
        self.dateTextView.text = [NSString stringWithFormat:@"%@ %@",
                                  [dayMonthDate stringFromDate:self.datePicker.date],
                                  [gmtAndYearFormatter stringFromDate:self.datePicker.date]];
    }
    

    So, I got result as Tue Sep 29 11:58:29 GMT+05:30 2015