Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

iphone - Problem combining a date and a time into a single NSDate

I am trying to combine the time value (hours, minutes, seconds) of one NSDate with the date value (day, month, year) of a second NSDate with this method:

+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {

    NSCalendar *gregorian = [[NSCalendar alloc]
        initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | 
        NSWeekdayCalendarUnit) fromDate:date];
    NSDateComponents *timeComponents = [gregorian components:(NSDayCalendarUnit | 
        NSWeekdayCalendarUnit) fromDate:time];

    NSDateComponents *comp = [NSDateComponents alloc];
    [comp setSecond:[timeComponents second]];
    [comp setHour:[timeComponents hour]];
    [comp setMinute:[timeComponents minute]];
    [comp setYear:[dateComponents year]];
    [comp setMonth:[dateComponents month]];
    [comp setDay:[dateComponents day]];

    NSDate *combDate = [gregorian dateFromComponents:comp]; 

    [gregorian release];
    [comp release];

    return combDate;
}

... but what it's returning is effectively gibberish (the year comes out as "1", for example). Anybody see what's wrong with this method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was using the wrong calendar components. Here's the corrected function (now for ARC):

+ (NSDate *)combineDate:(NSDate *)date withTime:(NSDate *)time {

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:
        NSGregorianCalendar];

    unsigned unitFlagsDate = NSYearCalendarUnit | NSMonthCalendarUnit 
        |  NSDayCalendarUnit;
    NSDateComponents *dateComponents = [gregorian components:unitFlagsDate 
        fromDate:date];
    unsigned unitFlagsTime = NSHourCalendarUnit | NSMinuteCalendarUnit 
        |  NSSecondCalendarUnit;
    NSDateComponents *timeComponents = [gregorian components:unitFlagsTime 
        fromDate:time];

    [dateComponents setSecond:[timeComponents second]];
    [dateComponents setHour:[timeComponents hour]];
    [dateComponents setMinute:[timeComponents minute]];

    NSDate *combDate = [gregorian dateFromComponents:dateComponents];   

    return combDate;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...