0
votes

I have been going up and down through all kinds of reference docs and examples over the web but I just can't get how to get what day, month, year, hours, minutes will it be for a given timestamp in Objective C. Any ideas? The code I'm using for the purpose is like this:

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:1286181000];
    unsigned int compFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;
    NSDateComponents *weekdayComponents = [[NSCalendar currentCalendar] components:compFlags fromDate:date];
    NSLog(@"%d %d, %d:%d", [weekdayComponents day], [weekdayComponents month], [weekdayComponents hour], [weekdayComponents minute]);
    [date release];
    [weekdayComponents release];

Although the timestamp is for a day in October, the output gives me 19th of December.

2
btw: neither date nor weekdayComponents have to be released. This will probably lead to a crash.Max Seelemann
i found this out just after i pasted this as it was indeed crashing and i was much too bothered with the wrong dates than the crashing. :D .thanks again.kumar

2 Answers

0
votes

The docs for dateWithTimeIntervalSince1970: say:

This method is useful for creating NSDate objects from time_t values returned by BSD system functions.

Can you show the code that gave you that magic number 1286181000? i.e. are you using a time_t value?

1
votes
//  for age validation  (dynamic age in date picker for 18-100 year)

 NSDate *today = [NSDate date];
    NSDateComponents *dc_min = [[[NSDateComponents alloc] init] autorelease];
    [dc_min setYear:-100];
    NSCalendar *cal_min = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDate *pastDate_min = [cal_min dateByAddingComponents:dc_min toDate:today  options:0];
    [datePicker setMinimumDate:pastDate_min];


    NSDateComponents *dc_max = [[[NSDateComponents alloc] init] autorelease];
    [dc_max setYear:-18];
    NSCalendar *cal_max = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDate *pastDate_max = [cal_max dateByAddingComponents:dc_max toDate:today  options:0];

    [datePicker setMinimumDate:pastDate_min];
    [datePicker setMaximumDate:pastDate_max];


    [datePicker setDate:[datePicker maximumDate]];
    [datePicker addTarget:self action:@selector(dateChanged:) forControlEvents:UIControlEventValueChanged];