1

我想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)
4

2 回答 2

2

您的输入字符串与格式不匹配:

format: @"yyyy-MM-dd HH:mm:ss"
input:  @"2013-7-25 5:16"
                        ^^^ missing :00

你可以用一个小的代码模块来修复它:

NSString *strSunRise = [NSString stringWithFormat:@"%d-%d-%d %d:%d:00", year, month, day, hour, minute];
                                                                  ^^^

(或通过:ss从格式字符串中删除)。

于 2013-07-25T12:05:54.243 回答
0

您的代码行:

NSString *strSunRise = [NSString stringWithFormat:@"%d-%d-%d %d:%d", year, month, day, hour, minute];

还应该包括秒,因为您正在使用带秒的日期格式化程序:

[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
于 2013-07-25T12:05:46.193 回答