vanilla_splsh
vanilla_splsh

Reputation: 163

Using NSDateFormatter to convert Int to Month String

I've been using another answer on here to do this. I'm storing my date as Int's in my DB but I want it to display as a full month in the UI. So on refresh/reload I'm trying to get the Int month value -> convert to String full month -> display that in textfield.

I've currently got it logging out the months and the full date but in the textfield on reload it shows as (null) / 05 / 1993

What am I doing wrong??

NSString *monthString = [self.datePickerFormat monthSymbols] [(self.birthdayMonth - 1)];
NSLog(@"%@",monthString);

NSString *dateString = [NSString stringWithFormat:@"%@ / %ld / %ld",monthString,(long)self.birthdayDay,(long)self.birthdayYear];
NSLog(@"%@",dateString);

self.birthdayField.text = [NSString stringWithFormat:@"%@",dateString];

self.birthdayMonth is an Integer. self.datePickerFormat is a NSDateFormatter that i've declared as a property. EDIT: Ok the logs don't come back with correct months so I don't know what's happening..

Is there another better way of doing this too? Thanks for any help!

Upvotes: 0

Views: 169

Answers (1)

psci
psci

Reputation: 933

To get month name from month number, use date formatter this way:

NSInteger month = 7;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *monthString = dateFormatter.monthSymbols[(month-1)];

Month name will be in your phone locale language. Although it's not recommended, you can override locale settings:

dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US"];

Upvotes: 2

Related Questions