How to calculate remaining Days, Hours, Mins and seconds from given date? - ios

In my app I need to get the days, hours, minutes and seconds from a given date which is coming from JSON response. Below is the date and time i'm getting:
"date_time" = "2017-01-31 08:30:00";
and need to calculate remaining like days: 6 hours: 18 minutes: 24 seconds: 30
End date will be today's date. I tried below code but it is giving me days in minus (I think it takes UTC timezone) and also tried many answers on SO.
NSString *start = [[self.eventsArray valueForKey:#"date_time"]objectAtIndex:0];
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *end = [date stringFromDate:[NSDate date]];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);
Somebody please help i'm stuck.

You are making mistake here, your fromDate should be the today date ie [NSDate date] and with toDate will be your startDate. So your code should be something like this.
NSString *end = [[self.eventsArray valueForKey:#"date_time"]objectAtIndex:0];
NSDateFormatter *date = [[NSDateFormatter alloc] init];
[date setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
//Start date
NSDate *startDate = [NSDate date];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"day : %ld H: %ld M : %ld S:%ld", [components day], (long)[components hour],(long)[components minute],(long)[components second]);

Call below method and pass your date
+(NSMutableString*) timeLeftSinceDate: (NSDate *) dateT {
NSMutableString *timeLeft = [[NSMutableString alloc]init];
NSDate *today10am = [NSDate date];
today10am = [self getPickerDateForString:[self getPickerDateForDate:today10am]];
NSInteger seconds = [today10am timeIntervalSinceDate:dateT];
NSInteger days = (int) (floor(seconds / (3600 * 24)));
if(days) seconds -= days * 3600 * 24;
NSInteger hours = (int) (floor(seconds / 3600));
if(hours) seconds -= hours * 3600;
NSInteger minutes = (int) (floor(seconds / 60));
if(minutes) seconds -= minutes * 60;
if(days) {
[timeLeft appendString:[NSString stringWithFormat:#"%ld Days ago", (long)days]];
}else if(hours) {
[timeLeft appendString:[NSString stringWithFormat: #"%ld h ago", (long)hours]];
}else if(minutes) {
[timeLeft appendString: [NSString stringWithFormat: #"%ld m ago",(long)minutes]];
}else if(seconds) {
[timeLeft appendString:[NSString stringWithFormat: #"Just now"]];
}
return timeLeft;
}
+ (NSString *)getPickerDateForDate:(NSDate *)dateVal
{
NSString * stringVal;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
stringVal = [dateFormatter stringFromDate:dateVal];
return stringVal;
}
+ (NSDate *)getPickerDateForString:(NSString *)dateString
{
NSDate * stringVal;
if (!dateFormatter)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
stringVal = [dateFormatter dateFromString:dateString];
return stringVal;
}

Related

How to get accuracy days completed

How to get accuracy days completed?
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd"];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitDay
fromDate:[dateFormatter dateFromString:startDate]
toDate:[dateFormatter dateFromString:endDate]
options:0];
return (CGFloat)components.day;
}
Example
The work is completed 3 days 12 hours 30Min
Expected result 3.55 Days.
The following example shows the days difference from the given date and today.
This might guide you to convert seconds, minutes, hours to days.
-(NSString*)timeDifferenceConversion:(NSString*)dateString
{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:#"en_US_POSIX"]];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate* firstDate = [dateFormatter dateFromString:dateString];
NSDate * now = [NSDate date];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *newDateString = [dateFormatter stringFromDate:now];
NSDate* secondDate = [dateFormatter dateFromString:newDateString];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
NSInteger ti = (NSInteger)timeDifference;
NSInteger minutes = (ti / 60) % 60;
NSInteger hours = (ti / 3600);
NSInteger days = (ti / 86400);
NSString* temp=#"";
if(minutes<=2 && hours<1 && days<1)
{
temp=#"now";
}
else if(minutes>2 && hours<1 && days<1)
{
temp=[NSString stringWithFormat:#"%ld minutes ago", (long)minutes];
}
else if(hours<=24 && days<1)
{
temp=[NSString stringWithFormat:#"%ld hours ago", (long)hours];
}
else if(days<=1)
{
temp=[NSString stringWithFormat:#"%ld day ago",(long)days];
}
else if(days>1)
{
temp=[NSString stringWithFormat:#"%ld days ago",(long)days];
}
return temp;
}
I suggest you calculate the difference in seconds between the two dates, then simply divide the result by the number of seconds in one day :
- (CGFloat)accuracyDaysCompleted:(NSString *)startDate and:(NSString *)endDate {
NSDate *date1 = [NSDate dateWithString: startDate];
NSDate *date2 = [NSDate dateWithString: endDate];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
return secondsBetween / 86400.0f;
}

How to get NSDate start of previous month?

I suppose that I ask duplicate question, but I can not find solution for me. I need to get 1st day of the previous month. As I understand I have to get calendar from today, subtract 1 month and set day to be 1st. After that I have to convert to date. Unfortunately I get last day of previous month.
I use following code:
NSDate *maxDate = [[NSDate alloc] init];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:maxDate];
[components setMonth:-1];
components.day = 1;
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#"%#", minDate);
EDIT:
Yes, it is duplicate, but answers in that question does not help me. I still get 30/09/2014 (when today is 17/11/2014) instead of 01/10/2014. I suppose that my problem is time of todays date.
Well, Here a new approach:
NSDate *today = [NSDate date];
NSDateFormatter *formatterYear = [[NSDateFormatter alloc] init];
[formatterYear setDateFormat:#"yyyy"];
NSDateFormatter *formatterMonth = [[NSDateFormatter alloc] init];
[formatterMonth setDateFormat:#"MM"];
[formatterMonth setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *yearString = [formatterYear stringFromDate:today];
NSString *monthString = [formatterMonth stringFromDate:today];
NSInteger month,year;
if ([monthString integerValue] == 1) {
year = [yearString integerValue] -1;
month = 12;
} else
{
year = [yearString integerValue];
month = [monthString integerValue]-1;
}
NSDateFormatter *exitFormatter = [[NSDateFormatter alloc] init];
[exitFormatter setDateFormat:#"yyyy-MM-dd"];
[exitFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"GMT"]];
NSString *stringDate;
if (month < 10) {
stringDate = [NSString stringWithFormat:#"%ld-0%ld-01",(long)year,(long)month];
} else {
stringDate = [NSString stringWithFormat:#"%ld-%ld-01",(long)year,(long)month];
}
NSDate *firstDatePreviousMonth = [exitFormatter dateFromString:stringDate];
NSLog(#"View the date: %#",[firstDatePreviousMonth description]);
Wrong calculation.
Use this code to set Month component.
[components setMonth:components.month -1];
NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
[dateFormatter1 setDateFormat:#"MM"];
NSString *stringCurrentDate = [dateFormatter1 stringFromDate:currentDate];
int monthInt= [stringCurrentDate intValue];
[dateFormatter1 setDateFormat:#"yyyy"];
NSString *dateString = [dateFormatter1 stringFromDate:currentDate];
int yearInt = [dateString intValue];
monthInt-= 1;
if (monthInt== 0) {
monthInt= 12;
yearInt -=1;
}
dateString = [NSString stringWithFormat:#"%#-01-%#",[#(monthInt)stringValue],[#(yearInt)stringValue]];
NSLog(#"this is previous month first date : %#",dateString);
run it as it is, obviously first day of month will be 01, so this is static here. your can change accordingly. happy coding
Try this:
NSDate *maxDate = [NSDate date];
NSCalendar *calendarCurr = [NSCalendar currentCalendar];
NSDateComponents *components = [calendarCurr components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitTimeZone | NSCalendarUnitSecond | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:maxDate];
[components setMonth:components.month - 1];
[components setDay:1];
NSDate *minDate = [calendarCurr dateFromComponents:components];
NSLog(#">>>>>>>>>>%#", minDate.description);

How to calculate NSDate between two NSDate in IOS

I want show whether particular office is opened or closed depends on the weekday
i am getting office timings from my server
NSString *open = #"10:00 AM";
NSString *close = #"6:00 PM";
NSDateFormatter *df11 = [[NSDateFormatter alloc]init];
[df11 setDateFormat:#"dd-MM-yyyy"];
NSString *date11=[df11 stringFromDate:[NSDate date]];
NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:#"dd-MM-yyyy hh:mm a"];
NSDate *date1 = [NSDate date];
NSString *dte1 = [df stringFromDate:date1];
date1 = [df dateFromString:dte1];
NSString *dte2 = [NSString stringWithFormat:#"%# %#",date11, open];
NSDate *date2 = [df dateFromString:dte2];
NSString *dte3 = [NSString stringWithFormat:#"%# %#",date11,close];
NSDate *date3 = [df dateFromString:dte3];
if([date1 compare:date2]==NSOrderedDescending && [date1 compare:date3]==NSOrderedAscending)
open=YES;
else
open=NO;
In this case i didn't get any problem, but for some other office i got like this
NSString *open = #"11:30 AM";
NSString *close = #"12:30 AM";/*means here day is changing but still i am using current date
for this case the above code is not working, bcoz of day changes, i am not getting any idea how to follow, i was struggling from last day for solution
please help me
thank you
get days between two dates
NSDate *date1 = [NSDate dateWithString:#"2013-08-08"];
NSDate *date2 = [NSDate dateWithString:#"2013-09-09"];
NSTimeInterval secondsBetween = [date2 timeIntervalSinceDate:date1];
int numberOfDays = secondsBetween / 86400;
NSLog(#"There are %d days in between the two dates.", numberOfDays);
You can also get different between two dates GO
Extract the week day and hour from the date and do an explicit test on them:
const NSInteger openHour = 10;
const NSInteger closeHour = 18;
NSDate *dateToTest = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSWeekdayCalendarUnit|NSHourCalendarUnit
fromDate:dateToTest];
BOOL open =
[components weekDay] >= [calendar firstWeekDay] &&
[components weekDay] < [calendar firstWeekDay] + 5 &&
[components hour] >= openHour &&
[components hour] < closeHour;

how to find days remaning in birthdate [duplicate]

This question already has answers here:
Calculate number of days remaining [duplicate]
(5 answers)
Closed 8 years ago.
i want to remaning days from array of birthdates im using following code for it
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
what wrong i am doing why i am not getting correct days
for(int i =0;i<_convertedBdates.count;i++){
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"dd/MM/YYYY"];
NSDate *firstdate = [tempFormatter dateFromString:[_convertedBdates objectAtIndex:i]];
NSString *curYear = [tempFormatter stringFromDate:[NSDate date]];
NSDate *secondDate = [tempFormatter dateFromString:curYear];
NSTimeInterval lastDiff = [firstdate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [secondDate timeIntervalSinceNow];
NSTimeInterval dateDiff = lastDiff - todaysDiff;
int day = dateDiff/(3600*24);
day = day -1;
NSLog(#" _newlymadeArray %#",[_convertedBdates objectAtIndex:i]);
NSLog(#" days %d",day);
[_daysremaining addObject:[NSString stringWithFormat:#"%d",day] ];
}
NSLog(#" days %#",_daysremaining);
try like this it will help you,
NSString *start = #"03/12/2013";
NSString *end = #"09/12/2013";
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd/mm/yyyy"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
fromDate:startDate
toDate:endDate
options:0];
NSLog(#"%d",[components day]);
Keep your code simple :
You can use a method and call it within your calculation block:
- (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar=[NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}

find total number of days between two dates in iphone

I would like to find total number of days between two dates.
e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?
NSDate *currentdate=[NSDate date];
NSLog(#"curretdate is ==%#",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-04-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *startdate = [tempFormatter dateFromString:#"15-01-2011 09:00:00"];
NSLog(#"startdate ==%#",startdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:#"dd-MM-yyyy HH:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:#"20-01-2011 09:00:00"];
NSLog(#"toDate ==%#",toDate);
int i = [startdate timeIntervalSince1970];
int j = [toDate timeIntervalSince1970];
double X = j-i;
int days=(int)((double)X/(3600.0*24.00));
NSLog(#"Total Days Between::%d",days);
Edit 1:
we can find date difference using following function :
-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
// Manage Date Formation same for both dates
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:date1];
NSDate *endDate = [formatter dateFromString:date2];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
return dayDiff;
}
from Abizern`s ans. find more infromation for NSDateComponent here.
NSCalendar *Calander = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:[NSDate date]] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *currentDate=[Calander dateFromComponents:comps];
NSLog(#"Current Date is :- '%#'",currentDate);
[dateFormat setDateFormat:#"dd"];
[comps setDay:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"MM"];
[comps setMonth:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"yyyy"];
[comps setYear:[[dateFormat stringFromDate:yourDate] intValue]];
[dateFormat setDateFormat:#"HH"];
[comps setHour:05];
[dateFormat setDateFormat:#"mm"];
[comps setMinute:30];
NSDate *reminderDate=[Calander dateFromComponents:comps];
//NSLog(#"Current Date is :- '%#'",reminderDate);
//NSLog(#"Current Date is :- '%#'",currentDate);
NSTimeInterval ti = [reminderDate timeIntervalSinceDate:currentDate];
//NSLog(#"Time Interval is :- '%f'",ti);
int days = ti/86400;
[dateFormat release];
[Calander release];
[comps release];
Hope It will work for you........
A simpler way of doing it is:
// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:#"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:#"01-01-2011"];
NSDate *endDate = [formatter dateFromString:#"25-03-2011"];
// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
// This just logs your output
NSLog(#"Start Date, %#", startDate);
NSLog(#"End Date, %#", endDate);
NSLog(#"%ld", [difference day]);
And the results are:
Start Date, 2011-01-01 00:00:00 +0000
End Date, 2011-03-25 00:00:00 +0000
83
Trying to use and manipulate seconds for calculating time differences is a bad idea. There are a whole load of classes and methods provided by Cocoa for Calendrical calculations and you should use them as much as possible.
Try this
- (int) daysToDate:(NSDate*) endDate
{
//dates needed to be reset to represent only yyyy-mm-dd to get correct number of days between two days.
NSDateFormatter *temp = [[NSDateFormatter alloc] init];
[temp setDateFormat:#"yyyy-MM-dd"];
NSDate *stDt = [temp dateFromString:[temp stringFromDate:self]];
NSDate *endDt = [temp dateFromString:[temp stringFromDate:endDate]];
[temp release];
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [gregorian components:unitFlags fromDate:stDt toDate:endDt options:0];
int days = [comps day];
[gregorian release];
return days;
}
//try it
if((![txtFromDate.text isEqualToString:#""]) && (![txtToDate.text isEqualToString:#""]))
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSDate *startDate = [formatter dateFromString:txtFromDate.text];
NSDate *endDate = [formatter dateFromString:txtToDate.text];
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];
int dayDiff = [difference day];
lblNoOfDays.text =[NSString stringWithFormat:#"%d",dayDiff];
}
to find the number of dates between start date to end date.
NSCalendar *cale=[[NSCalendar alloc]initWithCalendarIdentifier:NSGregorianCalendar];
unsigned unitFlags=NSMonthCalendarUnit| NSDayCalendarUnit;
NSDateComponents *comp1=[cale components:unitFlags fromDate:startDate toDate:endDate options:0];
NSInteger days=[comp1 day];
NSLog(#"Days %ld",(long)days);
NSDate *dateA;
NSDate *dateB;
NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
fromDate:dateA
toDate:dateB
options:0];
NSLog(#"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
//write this code in .h file
{
NSDate *startDate,*EndDate;
NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
[super viewDidLoad];
Date_Formatter =[[NSDateFormatter alloc]init];
[Date_Formatter setDateFormat:#"dd-MM-yyyy"];
UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:#"Next"
style:UIBarButtonItemStyleDone target:self action:#selector(doneWithNumberPad)],nil];
[numbertoolbar sizeToFit];
Txt_Start_Date.inputAccessoryView = numbertoolbar;
[Txt_Start_Date setInputView:Picker_Date];
Txt_End_Date.inputAccessoryView = numbertoolbar;
[Txt_End_Date setInputView:Picker_Date];
[Picker_Date addTarget:self action:#selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{
if ([Txt_Start_Date isFirstResponder])
{
[Txt_Start_Date resignFirstResponder];
[Txt_End_Date becomeFirstResponder];
}
else if([Txt_End_Date isFirstResponder])
{
[Txt_End_Date resignFirstResponder];
startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
Lab_Total_Days.text =[NSString stringWithFormat:#"%ld",components.day];
}
}
Please try this. Hope it helps you...
NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:#"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:#"MM/dd/YYYY HH:mm "] // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(#"%#f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];

Resources