Question

I want to concatenate 2 NSDates via NSDateComponents and [NSString stringWithFormat] to [dtFormatter dateFromString]. the first one has a complete format consisting of yyyy-MM-dd HH:mm:ss. But The second one has just information about hour and minute. So I want the second date to have all other information from the first date excepting seconds (will be added automatically?). I think everything works well until dtFormatter formats string to date. I already searched on stackoverflow but no solution could fix my issue:

my code:

//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]);

output:

strSunRise 2013-7-25 5:16 
(null)
dateOutput (null)
Was it helpful?

Solution

Your input string does not match the format:

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

You can fix it with a small code mod:

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

(or by removing :ss from the format string).

OTHER TIPS

Your line of code:

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

should also include seconds because you are using date formatter with seconds:

[dtFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top