获取iPhone提前1年的月份和年份 [英] Get Month and year of 1 year advance in iPhone

查看:55
本文介绍了获取iPhone提前1年的月份和年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要获取下一年的月份名称和年份并存储在数组中.我的意思是说假设今天是2012年9月,我需要月份名称和年份,直到2013年8月为止.

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

推荐答案

使用NSMonthCalendarUnit作为当前日历的components参数来获取当前月份的数字,例如9月为9,然后是本年的NSYearCalendarUnit,例如2012.然后在for循环中使用这些循环,该循环使用模数算法将舍入到下一年.

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.

如果for循环中的月份号小于当前月份,则使用当前年份加1作为下一年,否则使用当前年份.

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.

请注意,使用NSMonthCalendarUnit时返回的月号从1开始,而monthSymbols的索引号从零开始.这意味着即使我们从9月的9开始,从这个数组中获得的月份是10月,也就是我们想要的下个月.

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++;
}

这篇关于获取iPhone提前1年的月份和年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆