Question

I have some reviews with the date that has been created, so I want that date be an amount of days and after be an amount of month. this is the code i get the date with:

NSDateFormatter * inputFormatter = [[NSDateFormatter alloc] init];
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss" ];

NSString * inputString = entry.createdAt;
NSDate * inputDate = [inputFormatter dateFromString:inputString];
double  timeInterval = [inputDate timeIntervalSinceNow];
dateLabel.text = [NSString stringWithFormat:@"%d",timeInterval];
Was it helpful?

Solution

Days is easy:

int days = timeInterval / (60.0 * 60.0 * 24.0); //< i.e. divide by seconds in a day

Months is harder. Do you want it to be really accurate? Or will assuming 30 days in a month do? If so then it's just:

int months = timeInterval / (60.0 * 60.0 * 24.0 * 30.0); //< i.e. divide by seconds in a month

To wrap that all together, you could do:

if (timeInterval < (60.0 * 60.0 * 24.0 * 30.0)) {
    dateLabel.text = [NSString stringWithFormat:@"%i days", (int)(timeInterval / (60.0 * 60.0 * 24.0))];
} else {
    dateLabel.text = [NSString stringWithFormat:@"%i months", (int)(timeInterval / (60.0 * 60.0 * 24.0 * 30.0))];
}

Is that what you want?

OTHER TIPS

You should look at NSCalendar components:fromDate:toDate:options method.

    NSDate *date = [[[NSDate alloc] init] autorelease];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:date toDate:inputDate options:0];
    int years = [components year];
    int months = [components month];
    int days = [components day];
    NSLog(@"Start date: %@ End Date: %@", date, inputDate);
    NSLog(@"year: %i months: %i days: %i", years, months, days);
    [date release];
    [calendar release];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top