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

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

Related

Finding the difference between two dates always prints 10

Following is my code to get current date.
-(NSString *) getCurrentDate {
NSDateFormatter *dateformater = [[NSDateFormatter alloc]init];
[dateformater setDateFormat:#"dd-MMM-yyyy"];
NSString *today=[dateformater stringFromDate:[NSDate date]];
return today;
}
Im using the following code to find the difference between current date and the date selected from pickerview
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd-MMM-yyyy"];
NSString *date = [dateFormat stringFromDate:picker.date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:GregorianCalendar];
NSCalendarUnit unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"dd-MMM-yyyy"];
NSDate *selectedDate = [f dateFromString:date];
NSDate *currentDate = [f dateFromString:[self getCurrentDate]];
NSDateComponents *currentDateComponent = [gregorianCalendar components:unitFlags fromDate:currentDate toDate:selectedDate options:0];
but the currentDateComponent.day always prints the value 10.
whats wrong with my code? how can i be able to find the difference between two dates?
I think components you are using is wrong it should but only NSCalendarUnitDay
My code is returning me correct difference (difference.day).
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:[NSDate date] toDate:enDate options:0];

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

-[__NSDate timeIntervalSinceReferenceDate]: message sent to deallocated instance?

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
(-[__NSDate timeIntervalSinceReferenceDate]: message sent to deallocated instance 0x147165f0)
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;
}
Above code looks fine and I tried in sample app, its working fine. Did you synthesize your date property? Also please cross check if your property is of type strong.

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

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