我希望通过NSDates
和NSDateComponents
将[NSString stringWithFormat]
连接到[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)
答案 0 :(得分:2)
您的输入字符串与格式不匹配:
format: @"yyyy-MM-dd HH:mm:ss"
input: @"2013-7-25 5:16"
^^^ missing :00
您可以使用小代码mod修复它:
NSString *strSunRise = [NSString stringWithFormat:@"%d-%d-%d %d:%d:00", year, month, day, hour, minute];
^^^
(或从格式字符串中删除:ss
)。
答案 1 :(得分:0)
您的代码行:
NSString *strSunRise = [NSString stringWithFormat:@"%d-%d-%d %d:%d", year, month, day, hour, minute];
还应该包括秒,因为您使用的是带有秒的日期格式化程序:
[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];