find total number of days between two dates in iphone - ios

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];

Related

incompatible pointer type sending NSString to parameter of type NSDate* _Nonnull ios Objective c

I have the following code. Here I tried two methods to get the date and time. If i use formatter it gives me the above error. If I do not use it the date format is not correct and plus the time which i get is also incorrect. Kindly help.
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
NSLog(#"Old Date and Time : %#",[formatter stringFromDate:[NSDate date]]);
this give me output like this 12-07-2016 18:32 which I want
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
pickupHoursLate = [calender dateByAddingComponents:components toDate:[formatter stringFromDate:[NSDate date]] options:0];
This Line gives me the error
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0];
This Line gives me the value 2016-07-12 15:02:51 +0000 after adding 2 hrs to current time but here the time is incorrect
Try this....
NSDate *pickupHoursLate;
NSDate *dropHoursLate;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSLog(#"Old Date and Time : %#",[formatter stringFromDate:[NSDate date]]); **<this give me output like this 12-07-2016 18:32 which I want>**
NSCalendar *calender = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
int pickHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"pickupPriorTimePeriod"] intValue];
[components setHour:pickHoursToAdd];
//Editing start
NSString *dateStr = [formatter stringFromDate:[NSDate date]] ;
NSDate *date = [formatter dateFromString:dateStr];
pickupHoursLate = [calender dateByAddingComponents:components toDate: date options:0]; **<This Line gives me the error>**
//Editing End
int dropHoursToAdd = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dropPriorTimePeriod"] intValue];
[components setHour:dropHoursToAdd];
dropHoursLate = [calender dateByAddingComponents:components toDate:[NSDate date] options:0]; **<This Line gives me the value "2016-07-12 15:02:51 +0000" after adding 2 hrs to current time but here the time is incorrect>**

selecting only working days from NSDate in objective c

My concern is..if am having text field with start date.when i am selecting date from calendar with day of Friday..then i want to skip weekend days saturday and sunday in enddate text field...i tried like this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = roundedUp;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setDay:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateFormat:#"yyyy-MM-dd"];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
while ([strNewDate compare:strCurrentDate] == NSOrderedAscending)
{
NSDateComponents *dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:strNewDate];
if (dateComponents.weekday == friday)
{
count = count+2;
NSLog(#"count = %d", count);
NSDateComponents *oneDay = [[NSDateComponents alloc] init];
[oneDay setDay:2];
NSString *endDate = [strNewDate dateByAddingTimeInterval:2*60*60*24];
// [oneDay setDay:2];
}
}
But I am not getting only week days… so can any one do the needful… thank u in advance :)
To get the next working day from now use the method isDateInWeekend of NSCalendar
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
// Strip the time portion of the date
NSDate *date = [calendar startOfDayForDate:[NSDate date]];
do {
// add 1 day until the result is not in a weekend
date = [calendar dateByAddingUnit:NSCalendarUnitDay value:1 toDate:date options:NSCalendarMatchNextTime];
} while (![calendar isDateInWeekend:date]);
NSLog(#"Next Workday: %#", date);

Thread1: EXC_BAD_ACCESS(code=1,address=0x5146a345)

i am trying to implement calendar. i have one label for year and two buttons for incrementing and decrementing year from calendar. i am getting this exception (Thread1: EXC_BAD_ACCESS(code=1,address=0x5146a345)) while clicking button(increment or decrement)my requirement is if i click right button my year should increase as well as if i click left button my year should decrease. my exception line is date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0]; could you please help to resolve this issue. this is my code
- (void)viewDidLoad
{
[super viewDidLoad];
date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)right:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
- (IBAction)left:(id)sender {
NSCalendar *cal = [NSCalendar currentCalendar];
date = [cal dateByAddingUnit:NSCalendarUnitYear value:1 toDate:date options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"YYYY"];
NSString *stringFromDate = [formatter stringFromDate:date];
yar1.text=stringFromDate;
}
You need a date component to change the date like this,
-(NSDate *)offsetYear:(int)numOfYears date:(NSDate*)date
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setYear:numOfYears];
return [[NSCalendar currentCalendar] dateByAddingComponents:offsetComponents
toDate:date options:0]; }
Pass the offset as 1 for right and -1 for left

Add 3 Hours to an NSDate's Hour

I want to add 3 hours to my current date. I am using the following code to add hours but it adds 6 hours to the current date.
NSDate *n = [NSDate date];
int daysToAdd = 3; // or 60 :-)
// set up date components
NSDateComponents *components1 = [[[NSDateComponents alloc] init] autorelease];
[components1 setHour:daysToAdd];
// create a calendar
NSCalendar *gregorian12 = [NSCalendar currentCalendar];
NSDate *newDate2 = [gregorian12 dateByAddingComponents:components toDate:n options:0];
NSLog(#"Clean: %#", newDate2);
Result is :-
2013-09-10 12:25:24.752 project[1554:c07] Clean: 2013-09-10 06:55:15 +0000
Try this
NSString *strCurrentDate;
NSString *strNewDate;
NSDate *date = [NSDate date];
NSDateFormatter *df =[[NSDateFormatter alloc]init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strCurrentDate = [df stringFromDate:date];
NSLog(#"Current Date and Time: %#",strCurrentDate);
int hoursToAdd = 3;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setHour:hoursToAdd];
NSDate *newDate= [calendar dateByAddingComponents:components toDate:date options:0];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];
strNewDate = [df stringFromDate:newDate];
NSLog(#"New Date and Time: %#",strNewDate);
Output
Current Date and Time: Sep 10, 2013, 1:15:41 PM
New Date and Time: Sep 10, 2013, 4:15:41 PM
NSDate *CurrentTimedate = [NSDate date];
NSLog(#"%#",CurrentTimedate);
NSDate *newDate = [CurrentTimedate dateByAddingTimeInterval:60*60*3];
NSLog(#"%#",newDate);
NSDate *newDate = [oldDate dateByAddingTimeInterval:hrs*60*60];

Trying to use NSDate for time only

I'm struggling to find a way to use NSDate for time only purposes.
I was trying to do the following code:
- (void)awakeFromInsert
{
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
self.periodDuration = [calendar dateFromComponents:comps];
NSLog(#"periodDuration: %#",self.periodDuration);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
self.firstPeriodStartTime = [calendar dateFromComponents:comps];
NSLog(#"firstPeriodTime: %#",self.periodDuration);
}
But the result I get is:
periodDuration: 0001-12-31 22:24:04 +0000
firstPeriodTime: 0001-12-31 22:24:04 +0000
The result I was expecting:
periodDuration: 45:00
firstPeriodTime: 08:00
What am I doing wrong? How can I fix this?
Thank you.
The log of date is misleading you, if you are forming a date with only a few components you will not get a proper date instance which uniquely identifies a date and time.
If you try with this code snipped you can find that if you are just converting the dates back to string it is just as you expect
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.minute = 45;
comps.second = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *periodDate = [calendar dateFromComponents:comps];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"mm:ss"];
NSLog(#"periodDuration: %#",[dateFormatter stringFromDate:periodDate]);
comps = [[NSDateComponents alloc] init];
comps.hour = 8;
comps.minute = 0;
NSDate *firstPeriodDate = [calendar dateFromComponents:comps];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"firstPeriodTime: %#",[dateFormatter stringFromDate:firstPeriodDate]);
periodDuration: 45:00
firstPeriodTime: 08:00
You can use NSDateFormatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm"];
NSLog(#"%#",[dateFormatter stringFromDate:[NSDate date]]);
Use a NSTimeInterval (which is, basically, a double containing the number of seconds). To store it in CoreData:
[NSNumber numberWithDouble:myTimeInterval];
As for formatting: If you want more than 24h displayed, use this:
NSUInteger seconds = (NSUInteger)round(myTimeInterval);
NSString *formattedDate = [NSString stringWithFormat:#"%02u:%02u:%02u",
seconds / 3600, (seconds / 60) % 60, seconds % 60];
NSLog(#"%#", formattedDate);
If you don't want more than 24h, you can use NSDate and NSDateFormatter again:
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:myTimeInterval];
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm:ss"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:#"UTC"]];
NSString *formattedDate = [dateFormatter stringFromDate:date];
NSLog(#"%#", formattedDate);
NSString *timeString;
timeString = [NSDateFormatter localizedStringFromDate:[NSDate date]
dateStyle:NSDateFormatterNoStyle
timeStyle:NSDateFormatterMediumStyle];
12:03:54 PM

Resources