Нет способа сохранить 0
в NSInteger
. Таким образом, вы можете выбрать один из подходов здесь -
Избегайте компонентов даты и даты перепечатки в другом формате, используя NSDateFormatter
NSCalendar * gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"MMMM d yyyy H:mm"];
NSDate * theDate = [dateFormatter dateFromString:@"January 1 2010 5:05"];
/* Using NSDateFormatter to get the desired format */
[dateFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSLog(@"%@", [dateFormatter stringFromDate:theDate]);
От компонентов даты
NSInteger flags = (NSHourCalendarUnit|NSMinuteCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit);
NSDateComponents * dateComponents = [gregorianCalendar components:flags
fromDate:theDate];
NSInteger hour = [dateComponents hour];
NSInteger minute = [dateComponents minute];
NSInteger year = [dateComponents year];
NSInteger month = [dateComponents month];
NSInteger day = [dateComponents day];
NSLog(@"%02ld-%02ld-%ld %02ld:%02ld", day, month, year, hour, minute);
Использование NSNumberFormatter (расширение предыдущего блока)
NSNumberFormatter * numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setPaddingCharacter:@"0"];
[numberFormatter setMinimumIntegerDigits:2];
NSString * hourString = [numberFormatter stringFromNumber:[NSNumber numberWithInteger:hour]];
NSString * minuteString = [numberFormatter stringFromNumber:[NSNumber numberWithInteger:minute]];
NSString * yearString = [numberFormatter stringFromNumber:[NSNumber numberWithInteger:year]];
NSString * monthString = [numberFormatter stringFromNumber:[NSNumber numberWithInteger:month]];
NSString * dayString = [numberFormatter stringFromNumber:[NSNumber numberWithInteger:day]];
NSLog(@"%@-%@-%@ %@:%@", dayString, monthString, yearString, hourString, minuteString);