Thursday 16 February 2017

Working with NSDate

In iOS development  it's very common to work with NSDate. NSDate object returns the current point of time .
    
 NSDate *currentDate = [NSDate date];
The  above line of code will return the current time with date .

Last week  I was working on an app, the requirement was to calculate the difference between two dates and show the difference in number of days.

For example say you have two dates in string as:

NSString * firstDate = @"2015-10-01 05:46:41 UTC"
NSString *secondDate = @"2015-11-01 05:46:41 UTC"

Now to calculate the difference between  two, first of all we have to convert these two string dates to NSDate object.

To convert the string into NSDate object, create a formatter(NSDateFormatter) with format which matches to your string date as:

 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
 [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ssZ"];

The first line will initialize the NSDateFormatter and the second line will set the date format, as we have our date in this format in this example .

Now we can get the NSDate for an string date. To get the date from string use formatter object as:

NSDate * startDate =  [formatter dateFromString: firstDate];
NSDate *EndDate = [formatter dateFromString: secondDate];

Now you we have two NSDate object. To get the difference between these two , we should check the which date is later . 

To compare two NSDate object , we use compare method as:

if ([EndDate compare: startDate]== NSOrderedDescending){
    //EndDate is later than startDate date

    NSTimeInterval secondsBetween = [EndDate timeIntervalSinceDate: startDate];
   int numOfdaysLeft = secondsBetween/86400 ;
                   
    } 

Summary
Here we create the NSDate object from string, compare two NSDate object and calculate the time interval between two NSDate object and finally get the number of days from time interval .


                

No comments:

Post a Comment