我想通過NSDateComponents
和[NSString stringWithFormat]
連接到2 NSDates
到[dtFormatter dateFromString]
。第一個格式由yyyy-MM-dd HH:mm:ss
組成。但第二個只有小時和分鐘的信息。所以我希望第二個日期從第一個日期除了秒以外的所有其他信息(將自動添加?)。我認爲一切正常,直到dtFormatter格式字符串爲止。我已經搜索了計算器,但沒有解決方案可以解決我的問題:NSDateFormatter dateFromString返回null
我的代碼:
//pDate has a complete date format
NSDateComponents *dateComponentsComplete = [[NSCalendar currentCalendar]
components:NSYearCalendarUnit |NSDayCalendarUnit | NSMonthCalendarUnit fromDate:self.pDate];
//sunRise has the incomplete format
NSDateComponents *dateComponentsIncompleteSunRise = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:self.sunRise];
NSInteger day = [dateComponentsComplete day];
NSInteger month = [dateComponentsComplete month];
NSInteger year = [dateComponentsComplete year];
NSInteger hour = [dateComponentsIncompleteSunRise hour];
NSInteger minute = [dateComponentsIncompleteSunRise minute];
//concatenate
NSString *strSunRise = [NSString stringWithFormat:@"%d-%d-%d %d:%d", year, month, day, hour, minute];
NSLog(@"strSunRise %@ ", strSunRise);
NSDateFormatter* dtFormatter = [[NSDateFormatter alloc] init];
[dtFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dtFormatter setTimeZone:[NSTimeZone systemTimeZone]];
[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate* dateOutput = [dtFormatter dateFromString:strSunRise];
NSLog(@"%@", [dateOutput class]);
NSLog(@"dateOutput %@ ", [dtFormatter stringFromDate:dateOutput]);
輸出:
strSunRise 2013-7-25 5:16
(null)
dateOutput (null)
真的,人!這個問題是否需要再問? –