从月份名称获取月份数字?

从月份名称获取月份数字?

问题描述:

快速问题,我有一个月份的名单,如JanFebMarApr...等,我想转换为1,2,3,4 ...等。我写了一些简单的代码来做到这一点,但只是好奇,如果有人知道一个方法来使用任何API。

Quick question, I have a list of months by name i.e. "Jan" "Feb" "Mar" "Apr" ... etc. that I want to convert into 1,2,3,4 ... etc. I have written some simple code to do this but was just curious if anyone knew a way to do this using any of the APIs.

快速回答:

NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"MMM"];
NSDate *aDate = [formatter dateFromString:@"Jul"];
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit fromDate:aDate];
NSLog(@"Month: %i", [components month]); /* => 7 */

查看 date formatters