Problem
I have a timestamp that I am converting to an NSDate. Now I need to extract the time. I have successfully extracted the time but the only problem I have is that if the minutes are 0, it displays “0” instead of “00”. So 11:00 would be shown as: “11:0”. Everything else works, for example 11:30 works fine.
Code
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[self.program.sd intValue]];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(kCFCalendarUnitHour | kCFCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];
NSLog(@"%d:%d", hour, minute);
Any suggestions? What have I done wrong? Is there a better way to extract both the hour and the minute at the same time rather than what I’ve done above?
Thanks!
Are you getting the right values back? If all you’re doing is displaying the time to the user, you should use
NSDateFormatterto create a string from the date object.Possibilities for format strings are documented in UTS #35: Locale Data Markup Language Appendix F: Date Format Patterns.