Showing posts with label month. Show all posts
Showing posts with label month. Show all posts

Tuesday, December 7, 2010

How to get day, month, year, hours, minutes, seconds from UIDatePicker


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.

UIDatePicker Component value


I have a UIDatePicker that shows (ex. April | 13 | 2010). I need to get each component value and set it as an integer so it can be put into three separate keys in a Plist.
MyMonth  Number  04
MyDay    Number  13
MyYear   Number  2010
I can set a text label by using:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateStyle = NSDateFormatterMediumStyle;
dateLabel.text = [NSString stringWithFormat:@"%@",
                                           df stringFromDate:datePkr.date]];
[df release];
But I just need to convert each component value to integer. Would it be easier creating a UIPickerView with date array and doing it that way?

To get a component from date picker, generate a NSDateComponents object from the calendar with -components:fromDate::
NSDateComponents* comps = [datePkr.calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit)
                                              fromDate:datePkr.date];
int myYear = [comps year];
int myMonth = [comps month];
int myDay = [comps day];

Followers