DatePicker not selecting the correct date - objective-c

I have a Button in my view.On tapping the Button you get a datepicker which defaults to today's date, the user can then select the date they want to search for events.
The problem is, no matter what date I select, it always returns the current day and adds this to my TextField which i have placed inside mu Button.Can any one tell me where I am wrong.am setting the date picker programatically.
Below is my code hopefully someone can help me out!
//displaying date picker while clicking on button
- (IBAction)startDateButtonAction:(id)sender
{
if ([popOverController isPopoverVisible]) {
[popOverController dismissPopoverAnimated:YES];
}
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController
UIView *popoverView1 = [[UIView alloc] init]; //view
datePicker =[[UIDatePicker alloc]init];//Date picker
datePicker.frame =CGRectMake(0,0,240, 150);
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setMaximumDate:[[NSDate date] dateByAddingTimeInterval:24*60*60*-6]];
[datePicker setMinimumDate:[DateFormatter getSubtractedDateForomCurrentDateWith:35]];
datePicker.date = [DateFormatter getDateFromString:startDateLabel.text];
datePicker.selected = YES;
[datePicker addTarget:self action:#selector(datePickerValue) forControlEvents:UIControlEventValueChanged];
[popoverView1 addSubview:datePicker];
popoverContent.view = popoverView1;
popOverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
[popOverController setPopoverContentSize:CGSizeMake(240, 150) animated:NO];
[popOverController presentPopoverFromRect:startDateButton.frame inView:headerView permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
//action function while selecting any of the date from date picker
- (void) datePickerValue
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-6];
NSDate *labelStartDate = datePicker.date;
startDate = [DateFormatter getOnlyDateComponentsFromDate:labelStartDate];
NSDate *labelEndDate = [self addDayToDate:startDate Number:6];
startDateLabel.text = [DateFormatter getDateStringddmmyyy:labelStartDate];
endDateLabel.text = [DateFormatter getDateStringddmmyyy:labelEndDate];
}
[including the functions that am used here]
//used for getting date components
+(NSDate *) getOnlyDateComponentsFromDate:(NSDate *)date
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
return dateOnly;
}
- (NSDate *) addDayToDate:(NSDate *)date Number:(int) number
{
NSDate *newDate = [date dateByAddingTimeInterval:60*60*24*number];
return newDate;
}
Iam using ARC.
here datePicker.date gives me only the current date even though I select any other dates

I found out my mistake at last..The problem was with my code where i set the maximum and minimum value for the datePicker.removing the code for setting maximum and minimum value the code works fine..

You need to initialise your datepicker like this.
_datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
_datePicker.tag=1951;
_datePicker.datePickerMode=UIDatePickerModeDate;
[_datePicker addTarget:self action:#selector(ageChanged:) forControlEvents:UIControlEventValueChanged];
[_actionSheet addSubview:_datePicker];
And for your this method: ageChanged:
-(void)ageChanged:(id)sender {
NSDate *datePicked = [_datePicker date];
NSLog(#"%#", datePicked);
formattedDate = [dateFormatter stringFromDate:datePicked];
}
and set dateFormatter as per your requirement.
while changing your date it will give you the date you have selected in date Picker.
I hope this will help you for date picker.

Related

Working with Date and Time separately using NSDatePickerView on Xcode

I have a part of app that set date and time of an appointment. For this, I have two NSDatePickerView. The first one I set to NSDatePickerModeDate, while the other one to NSDatePickerModeTime. But actually they should be referring to a same NSDate object inside a NSMutableDictionary entry. I know about NSDatePickerModeDateTime, but I need the date and time to be picked separatedly.
I know how to set up the NSDatePickerView to show and hide and event control and such, but at the event control UIControlEventValueChanged fire for NSDatePickerView, I'm confused on how to code the change for this, and also how to initialise the pickers (datePicker.date = today, timePicker.date = "9:00 AM")
#interface MyViewController () {
NSMutableDictionary *data;
}
#end
#implementation MyViewController
#synthesize datePicker, timePicker;
- (void) viewDidLoad {
[super viewDidLoad];
data = [[NSMutableDictionary alloc] init];
[data setObject:[NSDate date] forKey:#"date"];
datePicker.datePickerMode = UIDatePickerModeDate;
timePicker.datePickerMode = UIDatePickerModeTime;
[datePicker addTarget:self action:#selector(changeDate:) forControlEvents:UIControlEventValueChanged];
[timePicker addTarget:self action:#selector(changeTime:) forControlEvents:UIControlEventValueChanged];
datePicker.date = data[#"date"]; //????
timePicker.date = data[#"date"]; //????
}
- (IBAction) changeDate:(id)sender {
UIDatePickerView *dp = (UIDatePickerView *)sender;
[data setObject:dp.date forKey:#"date"]; //????
}
- (IBAction) changeTime:(id)sender {
UIDatePickerView *tp = (UIDatePickerView *)sender;
[data setObject:tp.date forKey:#"date"]; //????
}
The part that I don't know how to code it is denoted by //????. I've read about NSDateFormatter, NSCalendar, and some kind of date components on some answers, but that was actually making me more confused as it also throws strings and structs into the mix, what to use to do what and when. Please help.
You can set both date pickers to the same date and time. The unused part is there but it isn't displayed and can't be changed. When the user changes the value of one date picker you have to set the other date picker to the same value.
- (IBAction)changeDate:(id)sender {
NSDatePicker *dp = (NSDatePicker *)sender;
[data setObject:dp.dateValue forKey:#"date"];
self.timePicker.dateValue = dp.dateValue;
}
- (IBAction)changeTime:(id)sender {
NSDatePicker *tp = (NSDatePicker *)sender;
[data setObject:tp.dateValue forKey:#"date"];
self.datePicker.dateValue = tp.dateValue;
}
u can try this
///Convert Full date to only date
- (IBAction) changeDate:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MM/dd/yyyy"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"date"];
}
///convert Date to only time format
- (IBAction) changeTime:(UIDatePickerView *)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"hh:mm a"];
NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
[data setObject:dateStr forKey:#"Time"];
}

Filtering json data and reloading the resulted data into myTableView

Im trying to load an events(data) (from json file) that matches today's date into my tableView when the today's button is pressed then only the data with today's date will be loaded there and when the future button is pressed the events with later dates will be loaded, the only problem I have here is when i run my program nothing is actually happening when I press in either of these UIbuttons, I got all the events regardless their date and without even clicking on any UIButton, u can see below some of my code, it would be great if someone could figure out what is the problem there and since Im not quiet sure about how to use predicate to filter the data:
#property (strong, nonatomic) NSArray *dateEvents;
#end
#implementation HomeViewController {
NSArray *_events;
NSArray *_dateEvents;
}
- (IBAction)upcomingEvents:(id)sender {
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"mama");
_dateEvents = [_events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Events * event, NSDictionary *bindings){
return [event.date isEqualToString:dateString];
}]];
self.myTableView.dataSource = self;
[self.myTableView reloadData];
NSLog(#"yes");
}
Thanks,
I'm not sure this will definitely help, because I can't see enough code so be certain that this is your problem, but you might find it useful to convert all the dates to NSDate objects (so that you can be certain that the problem is NOT that the strings are actually not equal), and then check whether the day is the current day, or not, by using this category method on NSDate:
NSDate+Extensions.m:
static NSCalendar* ___calendar;
#implementation NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:self];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
-(NSCalendar*)currentCalendar
{
if(___calendar == nil)
{
___calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
}
return ___calendar;
}
#end
NSDate+Extensions.h
#interface NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date;
#end

UILocalnotification is not firing

Since i just cant get a good answer for this and spend so much time on this, i will ask my question in details
All i want is to create an alarm according to date picker.
setting alarm to 10 seconds from now, is works great .
UIDatePicker, is works (print the date-but not the date i have picked, but 3 hours later)
i know there is an issue with local times, but i just cant find any good explanation.
my propose, and i guess that almost everyone,is not getting involve in local times, but to take each user's clock, and set alarm according to his time.
my code, is not working, i dont know why. its not firing(only if i set it to 10 seconds later)
please, i know that time zone should be different or something, but if you can explain what exactly to do and how, that would be great . thanks.
this is the code :
-(void)setDatePicker
{
CGRect pickerFrame = CGRectMake(0,265,0,0);
UIDatePicker *myPicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
[myPicker addTarget:self action:#selector(pickerChanged:) forControlEvents:UIControlEventValueChanged];
[[[CCDirector sharedDirector] view] addSubview:myPicker];
[myPicker release];
}
-(void)pickerChanged:(UIDatePicker*) datePicker
{
date=datePicker.date;
NSLog(#"value: %#",date);
}
and the local notification :
-(void) scheduleNotificationForDate: (NSDate*)theDate
{
/* Here we cancel all previously scheduled notifications */
[[UIApplication sharedApplication] cancelAllLocalNotifications];
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
//NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
//[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
//NSDate *notificationDate = [dateFormat stringFromDate:theDate];
localNotification.fireDate = theDate;
NSLog(#"Notification will be shown on: %#",localNotification.fireDate);
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = [NSString stringWithFormat:
#"Your notification message"];
localNotification.alertAction = NSLocalizedString(#"View details", nil);
localNotification.soundName = UILocalNotificationDefaultSoundName;
localNotification.applicationIconBadgeNumber = -1;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}
i got it .
i had to change the format and it worked.
nothing that relates to zones.
NSDateFormatter *dateFormat = [[[NSDateFormatter alloc]init]autorelease];
[dateFormat setDateFormat:#"YYYY-MM-dd HH:mm:ss"];
NSString *dateString = [dateFormat stringFromDate:date];
NSDate *notificationDate = [dateFormat dateFromString:dateString];
localNotification.fireDate = notificationDate;

ios how to change an image at specific time

I have an image that i want to display as a sun during daytime i.e. from 6am to 6pm, and moon from 6pm to 6am.
I have successfully implemented that but the problem is the image would not change when it reaches the specified time unless re-run the apps before the image change itself.
I don't want to use NSTimer to check the time, like every second. The only possible solution i think of is using NSLocalNotification but I'm a newbiew to it. any help? =)
-(void) dayOrNight
{
NSDate* date = [NSDate date];
NSDateFormatter* dateFormat = [[NSDateFormatter alloc]init];
[dateFormat setDateFormat:#"HHmm"];
NSString* dateString = [dateFormat stringFromDate:date];
NSNumber* currentTime = [NSNumber numberWithInt:[dateString intValue]];
NSNumber* daytime = [NSNumber numberWithInt:600];
NSNumber* nightime = [NSNumber numberWithInt:1800];
NSLog(#"current time: %#",dateString);
dayNight = [[UIImageView alloc] initWithFrame:CGRectMake(265, 10, 50, 50)];
if ( [currentTime doubleValue] >= [daytime doubleValue] && [currentTime doubleValue] <= [nightime doubleValue] )
{
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
else
{
dayNight.image = [UIImage imageNamed:#"moon.png"];
}
[self.view addSubview:dayNight];
}
Local notification should be fine, I guess.
Here you can get all needed code snippets to implement execution of dayOrNight method at needed time. Also, you shouldn't add new view every time you change the picture.
I think it is impossible to do without NSTimer. U can set refreshTime by yourself (for example 1 min/ if u don`t want to do it every second)))
Or u can call this method in other methods, which are working in your class every time...
maybe u have some object, which u use during your class is working...
-(IBAction)myButtonWhichIPressDuringIworkHere {
///some actions
[self dayOrNight];
}
In other case you should to use NSTimer
you don't need to check the time at every second.
this is one of the possible solutions. it has been tested on real device only.
your UIYourViewController.m
- (void)viewWillAppear:(BOOL)animated {
NSDate *_currentDate = [NSDate date];
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00AM +0000'"]; // set the morning date here
NSString *_morningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd' 06:00PM +0000'"]; // set the evening date here
NSString *_eveningDateString = [_dateFormatter stringFromDate:_currentDate];
[_dateFormatter setDateFormat:#"yyyy-MM-dd hh:mma zzz"];
NSDate *_morningDate = [_dateFormatter dateFromString:_morningDateString];
NSDate *_eveningDate = [_dateFormatter dateFromString:_eveningDateString];
NSTimeInterval _intervalToMorningDate = [_morningDate timeIntervalSinceDate:_currentDate];
NSTimeInterval _intervalToEveningDate = [_eveningDate timeIntervalSinceDate:_currentDate];
if (_intervalToMorningDate > 0) {
// now it is night
dayNight.image = [UIImage imageNamed:#"moon.png"];
[self performSelector:#selector(replaceTheBackgoundForMorning) withObject:nil afterDelay:_intervalToMorningDate];
} else {
// now it is daytime
dayNight.image = [UIImage imageNamed:#"Sun.png"];
[self performSelector:#selector(replaceTheBackgoundForEvening) withObject:nil afterDelay:_intervalToEveningDate];
}
}
- (void)viewDidDisappear:(BOOL)animated {
[NSObject cancelPreviousPerformRequestsWithTarget:self];
}
and finally you should add them to your same .m file:
-(void)replaceTheBackgoundForMorning {
// reaplce the backgound here
dayNight.image = [UIImage imageNamed:#"Sun.png"];
}
- (void)replaceTheBackgoundForEvening {
// reaplce the backgoung here
dayNight.image = [UIImage imageNamed:#"moon.png"];
}

Increase NSDate +1 day method Objective-C?

This is my method I use for increasing by one day in my navigationBar, and setting the name of the day as a title. I know it's wrong because I set "today" variable every time its called. But I can't figure out how to increase +1 day every time I call this method.
-(void)stepToNextDay:(id)sender
{
today = [NSDate date];
NSDate *datePlusOneDay = [today dateByAddibgTimeInterval:(60 * 60 * 24)];
NSDateFormatter *dateformatterBehaviour = [[[NSDateFormatter alloc]init]autorelease];
[dateFormatter setDateFormat:#"EEEE"];
NSString *dateString = [dateFormatter stringFromDate:datePlusOneDay];
self.navigationItem.title = datestring;
}
Store the date your are showing in a property (ivar, ...) of your view controller. That way you can retrieve the current setting when you go to the next day.
If you want to reliably add dates, use NSCalendar and NSDateComponents to get a "1 day" unit, and add that to the current date.
NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar] autorelease];
NSDateComponents* components = [[[NSDateComponents alloc] init] autorelease];
components.day = 1;
NSDate* newDate = [calendar dateByAddingComponents: components toDate: self.date options: 0];
As from iOS 8 NSGregorianCalendar is depricated, the updated answer will be,
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate *newDate = [calendar dateByAddingComponents:components toDate:today options:0];
Swift Code:
var today:NSDate = NSDate()
let calender:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
var components:NSDateComponents = NSDateComponents()
components.setValue(1, forComponent: NSCalendarUnit.CalendarUnitDay)
var newDate:NSDate! = calender.dateByAddingComponents(components, toDate:today, options: NSCalendarOptions(0))