If/Else statement for Date..iPhone SDK - iphone

I have this bit of code here. How would I write an if/else statement to determine whether the itemDate has already passed? So if itemDate has already passed, then localnotif.fireDate should be what it is now, plus 86400 (for 24 hours) else leave as is.
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:item.day];
[dateComps setMonth:item.month];
[dateComps setYear:item.year];
[dateComps setHour:item.hour];
[dateComps setMinute:item.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = [itemDate dateByAddingTimeInterval:-(minutesBefore*60)] ;
NSLog(#"fireDate is %#",localNotif.fireDate);
localNotif.timeZone = [NSTimeZone defaultTimeZone];

You can retrieve the current date using [NSDate date].
NSDate has this really convenient method called laterDate: that compares a date with the receiver and returns which ever one is later.
You can see if two dates are equal using isEqual:
In other words:
NSDate * notificationDate = [localNotif fireDate];
NSDate * now = [NSDate date];
if ([[now laterDate:notificationDate] isEqual:now]) {
//in a comparison between "now" and "notificationDate", "now" is the later date,
//meaning "notificationDate" has already passed
notificationDate = [notificationDate dateByAddingTimeInterval:86400];
}
[localNotif setFireDate:notificationDate];

Related

Adding Month to NewDate

I am new to iPhone developer,
I made a one custom date in that custom date i want to add 1 month or 3 month or 6 month according to frequency.
i want to add month till newDate is less then today's date.
here is my code snippet,
while ([today compare:temp] == NSOrderedDescending)
{
NSLog(#"inside----- today=%#,temp=%#",today,temp);
//add to dates
NSDateComponents *newComponents= [[NSDateComponents alloc] init];
if([FrequencySelText isEqualToString:#"Monthly"]){
[newComponents setMonth:1];
}
if([FrequencySelText isEqualToString:#"Quarterly"]){
[newComponents setMonth:3];
}
if([FrequencySelText isEqualToString:#"Half - Yearly"]){
[newComponents setMonth:6];
}
if([FrequencySelText isEqualToString:#"Yearly"]){
[newComponents setMonth:12];
}
// get a new date by adding components
NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy"];
NSString *newDate = [formatter stringFromDate:temp];
NSLog(#"new date=%#",newDate);
}
My Log shows: inside----- today=2012-07-11 14:41:27 +0000,temp=2012-04-12 03:00:00 +0000
I am getting Exc_bad_access at this line, NSDate* temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0];
Any help will bw appreciated.
Providing value to temp again then no need provide NSDate object type again. Here u already have NSDate *temp then why r u using same name again for NSDate object
temp= [[NSCalendar currentCalendar] dateByAddingComponents:newComponents toDate:temp options:0]
Maybe try this one:
NSDateComponents *dateComponents = [[[NSDateComponents alloc] init] autorelease];
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[dateComponents setMonth:1]; // Sample Add
NSDate *tempDate = [gregorian dateByAddingComponents:dateComponents toDate: temp options:0];
NSString *strTempDate = [dateFormat stringFromDate:tempDate];
// New Date on strTempDate

set datepicker at a specific time

Hi guys i have a problem
i my code i set a datepicker with the date of today, after that if the user change the picker i set a alarm to ring at the date of picker.
How can i "block the picker" on these date?
here my code, i hope in your help
NSDate *pickerDate = [NSDate date];
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
// Divisione della data in fattori
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
// Set Up dell'alarme considerando tutti i fattori
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
//Notifica in meno di un minuto
[dateComps setSecond:0];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
[alarmDatePickerUno setDate:itemDate animated:YES];
[alarmDatePickerDue setDate:itemDate animated:YES];
}
// ALARM UNO
// Set Allarme Uno
-(IBAction)setAlarmUno:(id)sender{
NSLog(#"picker in allarme");
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
//Setting dell'allarme in base al picker
AlarmDateUno = [alarmDatePickerUno date];
NSLog(#"allarme settata alle");
NSLog(#"%#", AlarmDateUno);
alarmDatePickerUno.userInteractionEnabled = NO;
alarmDatePickerDue.userInteractionEnabled = NO;
EDIT AFTER CLARIFICATION
If you want to use a date between app launches, you need to persist the date somehow. I would suggest using NSUserDefaults, but you could also go for the more complicated solution of Core Data. Using NSUserDefaults you would check every time you create your UIDatePicker for the saved value and use that to initialize the picker.
// Get the date
NSDate *unoDate = [[NSUserDefaults standardUserDefaults] objectForKey:#"PickerUnoKey"];
if (unoDate) { // If we have a persisted date, we set the date of the datePicker
[alarmDatePickerUno setDate:unoDate animated:NO];
}
Then when the user changes the value of the picker, you need to store the new value.
// When the datePicker value has changed, we store the value
[[NSUserDefaults standardUserDefaults] setObject:alarmDatePickerUno.date forKey:#"PickerUnoKey"];

iOS Fire local notification every day on specific time

I am trying to fire a local notification every day on 12:01 AM , but I don't know why my code does not work. Would you please help me to find the problem?
local = [[UILocalNotification alloc]init];
NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSPersianCalendar];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
//edited:
[dateComps setYear:1390]; //2012
[dateComps setMonth:10]; //1
[dateComps setDay:9]; //29
local.repeatInterval = 5;
[dateComps setHour:00];
[dateComps setMinute:1];
[dateComps setSecond:00];
local.fireDate = [calendar dateFromComponents:dateComps];
local.alertBody = #"HELLO";
local.alertAction = #"View";
local.applicationIconBadgeNumber = 1;
[[UIApplication sharedApplication]scheduleLocalNotification:local];
You're not setting the notification's repeatInterval property and your date components are missing a month, year and day. The defaults are zero, so your fireDate is way back in the past.
Also, you might want to be using NSGregorianCalendar instead of NSPersianCalendar.

Pass value of kCFCalendarUnitWeekday

I want to set an alarm on a particular day. I don't understand how to set the value of kCFCalendarUnitWeekday. Here is my code:
NSDateComponents *components = [[NSDateComponents alloc] init];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
localNotif.fireDate = selected;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatCalendar = [NSCalendar currentCalendar];
if (isSun) {
[components setWeekday:1];
[localNotif setRepeatInterval:(NSInteger)components];
}
if (isMon) {
[components setWeekday:2];
[localNotif setRepeatInterval:(NSInteger)components];
}
Thank you.
Ok here is some code to get you in the right direction:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:NSWeekdayCalendarUnit|NSYearCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:[NSDate date]];
// this will set the weekday to sunday
[components setWeekday:1];
// this is a new date on sunday
NSDate * newDate = [gregorian dateFromComponents:components];
You still have to find out whether the newDate is in the past, so it won't fire.
You actually have your code ready:
// ... init code ...
// *** this the important date ***
localNotif.fireDate = dateOnASunday;
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.repeatCalendar = NSWeekCalendarUnit;
... // add body etc. ...
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
[localNotif release];
Create a method around this snippet and pass the date with a parameter so you can reuse it. You only have to put in a date which should be the first fire date and it'll repeat every week. You just have to pass in a date on a Sunday or Wednesday.
You set a repeat interval like this:
// repeats notification on a weekly basis
localNotif.repeatCalendar = NSWeekCalendarUnit;
The repeatCalender property is of type NSCalendarUnit which is an enum.

How i campare two dates in Iphone?

I want to set date and time two days after my current date and time.How i set it using NSDate and dateformatter. I want compare date after two days, it was perviously set or not.
I write code now for it,
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDate *pickerDate = [self.datePicker date];
NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit )
fromDate:pickerDate];
NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
fromDate:pickerDate];
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:00];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
appDelegate.setTimerByUser = [itemDate retain];
How i compare it with current time and date?
Thanks
Look in NSDate.h and read Apple's docs for the -compare function on NSDates.
You can do for example:
NSDate *now = [NSDate date];
NSDate *future = [now dateByAddingTimeInterval: 2 * 24 * 60 * 60]; // add two days
if ( [now compare: future] == NSOrderedAscending ) {
// now is earlier than future so we will always get here
} else {
// never reached but illustrates how you might use compare
}
I think you need NSDateComponents. You can use this class to get year, month, day, and other attributes about date and time.
NSDate * now = [NSDate date];
NSDate * twoDaysFromNow = [now dateByAddingTimeInterval:(2 * 24* 60 * 60)];
You can compare with NSDate's -earlierDate: or -laterDate: methods.