本文介绍了NSDate减去一个月的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要两个NSInteger一年,一个月回去一个月。例如现在 2011-01 我如何才能获得 2010-12 。添加是一回事,但我想减去。
I want two NSInteger year, month to go one month back. e.g. now is 2011-01 how can I get 2010-12. adding is one thing, but I want to subtract.
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
[calendar release];
NSString * pdf_name = [NSString stringWithFormat:@"file_%d_%02d.pdf", year, month];
greets endo
greets endo
编辑:我的解决方案
NSCalendar *calendar= [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
BOOL substractOneMonth = YES;
if (substractOneMonth) {
if (month==1) {
year--;
month = 12;
}else {
month--;
}
}
[calendar release];
NSString * pdf_name = [NSString stringWithFormat:@"file_%d_%02d.pdf", year, month];
推荐答案
此示例代码来自iPhone的日期和时间编程指南。
This sample code is from iPhone's Date and Time Programming Guide.
NSDate *today = [[NSDate alloc] init];
NSLog(@"%@", today);
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setMonth:-1]; // note that I'm setting it to -1
NSDate *endOfWorldWar3 = [gregorian dateByAddingComponents:offsetComponents toDate:today options:0];
NSLog(@"%@", endOfWorldWar3);
我希望这有帮助!
这篇关于NSDate减去一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!