开发者

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 开发者_JAVA技巧time in the datepicker (because the datepicker's mode is the time one). How can i do this?


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜