Andrew
Andrew

Reputation: 16051

Set an NSDate object to custom date, combined with datepicker date?

I want to make an NSDate object which has the date set as the current date, but the time set as the time in the datepicker (because the datepicker's mode is the time one). How can i do this?

Upvotes: 1

Views: 920

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90127

and if you really want to use a custom date use something like this.

- (IBAction)dpChange:(UIDatePicker *)sender {
    // replace this with your custom date. 
    NSDate *myCustomDate = [NSDate dateWithTimeIntervalSinceNow:7*24*60*60];

    NSInteger dateFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:dateFlags fromDate:myCustomDate];

    NSDate *myCustomTime = [sender date];
    NSInteger  timeFlags = NSHourCalendarUnit | NSMinuteCalendarUnit;
    NSDateComponents *timeComponents = [[NSCalendar currentCalendar] components:timeFlags fromDate:myCustomTime];

    NSDateComponents *newComponents = [[[NSDateComponents alloc] init] autorelease];
    [newComponents setYear:[dateComponents year]];
    [newComponents setMonth:[dateComponents month]];
    [newComponents setDay:[dateComponents day]];
    [newComponents setHour:[timeComponents hour]];
    [newComponents setMinute:[timeComponents minute]];
    [newComponents setSecond:0];
    NSDate *newDate = [[NSCalendar currentCalendar] dateFromComponents:newComponents];

    NSLog(@"    Date: %@", myCustomDate);
    NSLog(@"    Time: %@", myCustomTime);
    NSLog(@"Combined: %@", newDate);
}

Upvotes: 1

Related Questions