Saturday, May 28, 2011

Calculate number of days between two dates in iPhone SDK

Hello Friends,

Today we will focus on another important issue while developing iPhone application. Most of the application contains date picker to select and display date in iPhone. Sometimes it is required to get number of day between two dates. For this calculation use following code.

To get correct number of days dates should be in yy-mm-dd format. For this use following code.

- (int) daysToDate:(NSDate*) endDate
{
    NSDateFormatter *temp = [[NSDateFormatter alloc] init];
    [temp setDateFormat:@"yyyy-MM-dd"];
    NSDate *stDt = [temp dateFromString:[temp stringFromDate:[NSDate date]]];
    NSDate *endDt =  [temp dateFromString:[temp stringFromDate:endDate]];
    [temp release];
    unsigned int unitFlags = NSDayCalendarUnit;
    NSCalendar *gregorian = [[NSCalendar alloc]
                             initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [gregorian components:unitFlags fromDate:endDt  toDate:stDt options:0];
    int days = [comps day];
   
    [gregorian release];
    return days;
}


Now use the following function where you want to get day difference.

NSString *str =[NSString stringWithFormat:@"%@ 00:00:00",[strdate substringToIndex:10]];
   NSDateFormatter *df = [[NSDateFormatter alloc] init];
   [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
   NSDate *dd = [df dateFromString:str];
   int d = [self daysToDate:dd];

Pass date in yy-mm-dd hh:mm:ss format. Example: 2011-05-28 00:00:00. Date should be in this format in str variable.

Thursday, May 26, 2011

Reverse an array in iPhone SDK

Hello Friends,

We some times need to reverse an array in some cases for such issues there is no ready made function to reverse an array in iPhone SDK.

Solution of this problem can be solved by following function.

- (NSMutableArray *)reverseArray:(NSMutableArray *)arr{
NSUInteger i = 0;
NSUInteger j = [arr count] - 1;
while (i < j) {
[arr exchangeObjectAtIndex:i withObjectAtIndex:j];
i++;
j--;
}
 return arr;
}
Above function will return same array with reverse value.

Setting Image on UIButton

Hello Friends,

Today we will throw a light on very common topic. We often required to set image on UIButton. Images can be set on UIButton with 2 methods. We can set image as button image and button background image.


Generally, We do not set image in button as image inside button because if we set button image then UIButton will enlarge according to the image size. So I prefer you to set Image on background so image will fit to button size.

To set Button title:
[btnImg setTitle:@"ABC" forState: UIControlStateNormal];

To set Background Image in button:
[btnImg setBackgroundImage:image forState: UIControlStateNormal];

To set Button Image:
[btnImg setImage:image forState: UIControlStateNormal];

Have a nice day..!!!