2011-07-10 82 views
15

我想改變NSDate的hh,mm,ss組件到另一個NSDate的 - 但由於某種原因,由於某種原因,時間被設置爲午夜。我無法弄清楚爲什麼!來自NSDateComponents的NSDate

這是代碼;

+ (NSDate *) fixTime:(NSDate*)fromDate toDate:(NSDate *) toDate { 
    NSCalendar *cal = [NSCalendar currentCalendar]; 
    [cal setTimeZone:[NSTimeZone localTimeZone]]; 
    [cal setLocale:[NSLocale currentLocale]]; 
    NSLog(@"fromDate=<%@>", [fromDate descriptionWithLocale:[NSLocale currentLocale]]); 
    NSLog(@"toDate= <%@>", [toDate descriptionWithLocale:[NSLocale currentLocale]]); 

    NSDateComponents *fromTimeComponents = [cal components:(NSHourCalendarUnit | 
                  NSMinuteCalendarUnit | 
                  NSSecondCalendarUnit ) fromDate:fromDate];        
    NSDateComponents *toDateComponents = [cal components:(NSYearCalendarUnit | 
                  NSMonthCalendarUnit | 
                  NSDayCalendarUnit  ) fromDate:toDate]; 
    NSDateComponents *toTimeComponents = [cal components:(NSHourCalendarUnit | 
                  NSMinuteCalendarUnit | 
                  NSSecondCalendarUnit ) fromDate:toDate]; 
    [toTimeComponents setHour:[fromTimeComponents hour]]; 
    [toTimeComponents setMinute:[fromTimeComponents minute]]; 
    [toTimeComponents setSecond:[fromTimeComponents second]]; 
    NSLog(@"toDateComponents year = %d", [toDateComponents year]);              
    NSLog(@"toDateComponents mon = %d", [toDateComponents month]);              
    NSLog(@"toDateComponents day = %d", [toDateComponents day]); 
    NSLog(@"toTimeComponents hour = %d", [toTimeComponents hour]);              
    NSLog(@"toTimeComponents min = %d", [toTimeComponents minute]);              
    NSLog(@"toTimeComponents sec = %d", [toTimeComponents second]); 

    NSDate *newDate = [cal dateFromComponents:toDateComponents]; 
    NSLogDebug(@"newDate=<%@>", [newDate descriptionWithLocale:[NSLocale currentLocale]]); 
    return [[newDate retain] autorelease]; 
} 

這裏是控制檯上的調試輸出。注意小時,分鐘,秒分量的值和newDate的最終值:

<Util.m:229> fromDate=<Monday, July 11, 2011 10:35:00 PM Pacific Daylight Time> 
    <Util.m:230> toDate= <Saturday, July 23, 2011 9:35:00 PM Pacific Daylight Time> 

    <Util.m:255> toDateComponents year = 2011 
    <Util.m:256> toDateComponents mon = 7 
    <Util.m:257> toDateComponents day = 23 
    <Util.m:258> toTimeComponents hour = 22 
    <Util.m:259> toTimeComponents min = 35 
    <Util.m:260> toTimeComponents sec = 0 
    <Util.m:266> newDate=<Saturday, July 23, 2011 12:00:00 AM Pacific Daylight Time> 

在此先感謝。

回答

30

你產生之日起關閉toDateComponents這裏,

NSDate *newDate = [cal dateFromComponents:toDateComponents]; 

toDateComponents的信息只有日期,月份和年份。它沒有時間細節。所以你得到12:00:00 AM。您已將時間信息存儲在toTimeComponents中,但未使用。如果你想這個工作,你將不得不添加時間信息到toDateComponents,並可能完全刪除toTimeComponents變量。

[toDateComponents setHour:[fromTimeComponents hour]]; 
[toDateComponents setMinute:[fromTimeComponents minute]]; 
[toDateComponents setSecond:[fromTimeComponents second]]; 
+1

謝謝 - 就是這樣! – Sam

相關問題