Установить для объекта NSDate пользовательскую дату в сочетании с датой выбора даты?

Я хочу создать объект NSDate, дата которого установлена ​​как текущая дата, но время установлено как время в средстве выбора даты (поскольку режим средства выбора даты является временным). Как я могу это сделать?


person Andrew    schedule 23.01.2011    source источник
comment
я думаю, вы можете просто использовать дату из средства выбора даты, потому что по умолчанию это будет текущая дата   -  person Felix    schedule 23.01.2011


Ответы (1)


и если вы действительно хотите использовать пользовательскую дату, используйте что-то вроде этого.

- (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);
}
person Matthias Bauch    schedule 23.01.2011