NSDate减去一个月

时间:2011-01-06 03:09:42

标签: iphone objective-c nsdate nsdatecomponents

我想要两个NSInteger一年,一个月回去一个月。例如现在 2011-01 我如何才能获得 2010-12 。添加是一回事,但我想减去。

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];

迎接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];

4 个答案:

答案 0 :(得分:57)

此示例代码来自iPhone的日期和时间编程指南。

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);

我希望这有帮助!

答案 1 :(得分:5)

虽然接受的答案有效,但它使用iOS 8.0中折旧的代码。在不使用弃用代码的情况下执行相同操作的另一种方法如下:

NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:-1];
date = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:date options:0];

答案 2 :(得分:5)

我建议为此目的创建扩展程序:

extension Date {

    func adding(months: Int) -> Date? {
        let calendar = Calendar(identifier: .gregorian)

        var components = DateComponents()
        components.calendar = calendar
        components.timeZone = TimeZone(secondsFromGMT: 0)
        components.month = months

        return calendar.date(byAdding: components, to: self)
    }

}

用法:

let now = Date()
let sixMonthsBefore = now.adding(months: -6)
let threeMonthsAfter = now.adding(months: 3)

答案 3 :(得分:1)

NSDate *date = [NSDate date];
NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];

month -= month - 1;

if (month < 1) {
 year -= 1;
 month = 12;
}

[calendar release];
NSString * pdf_name = [NSString stringWithFormat:@"file_%d_%02d.pdf", year, month];