我想NSDates
通过NSDateComponents
和[NSString stringWithFormat]
连接2 [dtFormatter dateFromString]
。第一个具有完整的格式,由yyyy-MM-dd HH:mm:ss
. 但是第二个只有关于小时和分钟的信息。所以我希望第二个日期拥有第一个日期的所有其他信息,除了秒数(会自动添加吗?)。我认为在 dtFormatter 格式化字符串之前一切正常。我已经在 stackoverflow 上进行了搜索,但没有解决方案可以解决我的问题:
我的代码:
//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)