Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to not lose '0' digits when using NSDateComponents.(iphone)

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

like image 600
James Avatar asked Jun 22 '11 18:06

James


1 Answers

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);
like image 78
Deepak Danduprolu Avatar answered Sep 25 '22 15:09

Deepak Danduprolu