Get the month number on behalf of the month?

Quick question, I have a list of months named "Jan" "Feb" "Mar" "Apr" ... etc. that I want to convert to 1,2,3,4 ... etc . I wrote simple code for this, but it was just curious if anyone knew about this using any of the APIs.

+4
source share
4 answers

Quick response:

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 .

+13
source

See the NSDateComponents Ref class. This will be the class you might want to consider.

+2
source

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

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

There is nothing more direct than that.

+2
source

For the Swift user, you can use:

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

0
source

Source: https://habr.com/ru/post/1394412/


All Articles