I am using Date Formatter, getting the NSDateComponents. And then extracting the individual time components such as hour, minute..etc.. How can I extract these components as NSIntegers without losing the '0' digits at the front of the number.
E.g is today was january 1 2010 5:05, it would print 1-1-2010-5:5 I want 01-01-2010-05:05
Any help would be appreciated
There is no way you can keep 0
in the NSInteger
. As such you can pick one of the approaches here –
Avoid date components and reprint date in a different format using 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]);
From Date components
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);
Using NSNumberFormatter (extending the previous block)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With