Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
289 views
in Technique[技术] by (71.8m points)

iOS: How to get a proper Month name from a number?

I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere in my code, there is an int representing a month. So: 1 would be January, 2 February, etc.

In my user interface, I would like to display this integer as proper month name. Moreover, it should adhere to the locale of the device.

Thank you for your insights

In the mean time, I have done the following:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];
[dateFormatter release];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[formatter release];

is this the way to do it? It seems a bit wordy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another option is to use the monthSymbols method:

int monthNumber = 11;   //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];

Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...