Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDate subtract one month

Tags:

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

EDIT: My solution

    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];
like image 275
endo.anaconda Avatar asked Jan 06 '11 03:01

endo.anaconda


2 Answers

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

I hope this helps!

like image 157
donkim Avatar answered Sep 19 '22 15:09

donkim


I suggest creating an extension for this purpose:

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

}

Usage:

let now = Date()
let sixMonthsBefore = now.adding(months: -6)
let threeMonthsAfter = now.adding(months: 3)
like image 40
Vadim Bulavin Avatar answered Sep 19 '22 15:09

Vadim Bulavin