我如何获得这十年的第一年和去年? 有人可以帮我这个吗?
我可以获得今年的第一个日期,但是这个十年呢?这是我的代码
[dateFormat setDateFormat:@"yyyy"];
NSString *theDateFormatted = [dateFormat stringFromDate: Sdate];
theDateFormatted = [NSString stringWithFormat:@"%@%@", theDateFormatted, @"-01-01 12:00:00 AM"];
// set last of month
NSString *theDateFormattedE = [dateFormat stringFromDate: Sdate];
theDateFormattedE = [NSString stringWithFormat:@"%@%@", theDateFormattedE, @"-12-31 11:59:59 PM"];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss a"];
Edate = [dateFormat dateFromString:theDateFormattedE];
Sdate = [dateFormat dateFromString:theDateFormatted];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB Status" message: theDateFormattedE delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
答案 0 :(得分:1)
首先从日期开始获取当前年份,如下所示:
NSDate *currentDate = [NSDate date];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; // Get necessary date components
NSInteger year = [components year];
然后,要获得十年的开始年份,
NSInteger firstYearOfTheDecade = year - (year % 10); //Add 1 to this if you want to start from x1
和去年
NSInteger lastYearOfTheDecade = firstYearOfTheDecade + 9;