fuzzygoat
fuzzygoat

Reputation: 26223

Get month number from month name?

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.

Upvotes: 5

Views: 6794

Answers (5)

Edgar Georgel
Edgar Georgel

Reputation: 602

For Swift User you can use:

Calendar.current.component(.month, from: date)
Calendar.current.component(.day, from: date)

Upvotes: 1

Fuhad saneen
Fuhad saneen

Reputation: 119

Swift 4, This works for me perfectly.

Calendar.current.component(.month, from: Date())
Calendar.current.component(.day, from: Date())

Upvotes: 0

El Developer
El Developer

Reputation: 3346

The easiest way to get a number is to get the index, that if the list of months is ordered:

NSLog(@"The number of the month is: %d.",[listOfMonths indexOfObject:@"Jan"]+1);

There's nothing more direct than this.

Upvotes: 2

Just a coder
Just a coder

Reputation: 16720

Check out the NSDateComponents class Ref. That would be the class you might want to consider using.

Upvotes: 2

djromero
djromero

Reputation: 19641

Quick answer:

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 */

See date formatters.

Upvotes: 15

Related Questions