Get Month and year of 1 year advance in iPhone

我怕爱的太早我们不能终老 提交于 2019-12-11 18:35:46

问题


in my app I need to get month name and year for next 1 year and store in array. I mean to say suppose today's September 2012, I need month name and year till August 2013.

Can you please tell me how will I get month and year? Thanx in advance


回答1:


Use the NSMonthCalendarUnit for the components parameter of the current calendar to get the number of the current month, e.g. 9 for September and then NSYearCalendarUnit for the current year, e.g. 2012. Then use these in a for loop which uses modulus arithmetic to wrap round to the next year.

If the month number in the for loop is less than the current month then use current year plus 1 as the next year, else use the current year.

Note that the month numbers returned when using NSMonthCalendarUnit start at 1, whereas the index numbers for the monthSymbols start at zero. Which means that even though we start with 9 for September, the month we get from this array is October, which is the next month that we want.

/*
 next 12 months after current month
 */

NSDateFormatter  *dateFormatter   = [[NSDateFormatter alloc] init];
NSDate           *today           = [NSDate date];
NSCalendar       *currentCalendar = [NSCalendar currentCalendar];

NSDateComponents *monthComponents = [currentCalendar components:NSMonthCalendarUnit fromDate:today];
int currentMonth = [monthComponents month];

NSDateComponents *yearComponents  = [currentCalendar components:NSYearCalendarUnit  fromDate:today];
int currentYear  = [yearComponents year];
int nextYear     = currentYear + 1;

int months  = 1;
int year;
for(int m = currentMonth; months < 12; m++){

    int nextMonth = m % 12;

    if(nextMonth < currentMonth){
        year = nextYear;
    } else {
        year = currentYear;
    }

    NSLog(@"%@ %i",[[dateFormatter monthSymbols] objectAtIndex: nextMonth],year);

    months++;
}



回答2:


NSDateFormatter is the key for any type of date (NSDate) formatting etc

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

To print date like September 17, 2012

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterLongStyle]; 
[df setTimeStyle:NSDateFormatterNoStyle];  
NSString *dateString = [df stringFromDate:[NSDate date]]; 
[df release];


来源:https://stackoverflow.com/questions/12462946/get-month-and-year-of-1-year-advance-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!