Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Some helpful date related code

    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 844
    Comment on it

    Get a date after n days

    -(NSDate*)getNextDayAfterDays:(int)numOfDays from:(NSDate*)date
        NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
        [offsetComponents setDay:numOfDays];
        NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:date options:0];
        NSLog(@"date %@ nextDate %@",date,nextDate);
        return nextDate;

    Get first day of month and first week day from any date

        NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *comp = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit| NSDayCalendarUnit   |NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit |NSWeekdayCalendarUnit ) fromDate:date];
        NSInteger thisDay = [comp day];
        NSInteger thisWeekday = [comp weekday];
        [comp setWeekday:1];
        [comp setDay:thisDay-thisWeekday+1];
        [comp setMinute:0];
        [comp setHour:0];
        [comp setSecond:1];
        NSDate *firstDayOfMonth = [gregorian dateFromComponents:comp];
        NSDateComponents *weekComp = [gregorian components:NSWeekdayCalendarUnit fromDate:firstDayOfMonth];
        int firstDayOfWeek = [weekComp weekday];
        NSLog(@"firstdayofmonth %@",firstDayOfMonth);
        NSLog(@"firstweekday %d",firstDayOfWeek);
        return firstDayOfMonth;

    Get difference between two dates

    -(int)getDifferenceBetweenDates:(NSDate *)startDate endDate:(NSDate*)endDate  
        NSCalendar *gregorian = [[NSCalendar alloc]
        NSUInteger unitFlags;
        NSDateComponents *components;
        unitFlags = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
        components = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
        NSLog(@"startdate %@ enddate %@",startDate,endDate);
        int day = [components day];
        return day;

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: