Working with Date and Time separately using NSDatePickerView on Xcode - objective-c

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

Related

Storing date value into Core Data in Objective C

Can anyone tell me please how to save only date value to Core Data using objective C? I am using UIDatePicker. I searched a lot, but couldn't find any. Can you be more specific because i am newbie. Thanks
Here is my code for adding data to core data database. But instead of formatting dates into string I would like to save as a NSdate. I am creating an calendar app that stores events into CoreData. Is there any help?
- (IBAction)btnSave:(UIBarButtonItem *)sender {
AppDelegate *delegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [delegate managedObjectContext];
NSManagedObject *dataRecord = [NSEntityDescription insertNewObjectForEntityForName:#"Scheduler" inManagedObjectContext:context];
[dataRecord setValue:self.txtBxCustomerName.text forKey:#"customerName"];
[dataRecord setValue: [self date] forKey:#"date"];
[dataRecord setValue:[self begin] forKey:#"startTime"];
[dataRecord setValue:[self end] forKey:#"endTime"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Error! %#", error);
}
[self dismissViewControllerAnimated:true completion:nil];
}
- (IBAction)datePicker:(id)sender {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM-dd-yyyy"];
NSString *string = [dateFormat stringFromDate:self.dateTime.date];
date = string;
}
- (IBAction)startTimePicker:(id)sender {
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"HH:mm"];
NSString *str = [timeFormat stringFromDate:self.startTime.date];
begin = str;
}
- (IBAction)endTimePicker:(id)sender {
NSDateFormatter *endTimeFormatt = [[NSDateFormatter alloc] init];
[endTimeFormatt setDateFormat:#"HH:mm"];
NSString *sting = [endTimeFormatt stringFromDate:self.endTime.date];
end = sting;
}
Get the date from the picker with
NSDate *chosenDate = myDatePicker.date;
and then set it to the desired attributed (in the example startDate) of your model, which should be define in Core Data as type Date
myCoreDataObject.startDate = chosenDate;
or even shorter
myCoreDataObject.startDate = myDatePicker.date;

DatePicker not selecting the correct date

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.

Objective C - can't set value in one method and access it from another

I am trying to do the following:
1) user clicks button start, it runs startTimer method, which sets a new [NSDate date].
2) user clicks button stop it runs stopTimer method, which retrieves the [NSDate date] value.
I can't get step number 2 working. I've set it in the .h file. If I copy the code from the start method into the stop method it works. So, I can set the [NSDate date]. But, this is not what I want. I want to be able to set it in the startTimer method. How do i go about this?
.h file
#interface StartTest : UIViewController {
IBOutlet UILabel *timer;
NSDate *startNSDate;
NSDate *start;
}
- (IBAction)startTimer;
- (IBAction)stopTimer;
- (NSDate *)setStart;
- (NSDate *)getStart;
#end
.m file:
#implementation Ash
- (IBAction)startTimer {
startNSDate = [NSDate date];
}
- (IBAction)stopTimer{
start = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
NSString *stringFromDate = [formatter stringFromDate:startNSDate]; // <<< this is where it fails
NSLog(#"stringfromdate: %#", stringFromDate);
}
startNSDate isn't retained and by the time you want to access it, it's already dealloc'd, hence you're trying to access garbage pointer
easiest solution for you will be
#interface StartTest : UIViewController {
IBOutlet UILabel *timer;
NSDate *startNSDate;
NSDate *start;
}
#property (nonatomic, strong) NSDate* startNSDate;
- (IBAction)startTimer;
- (IBAction)stopTimer;
- (NSDate *)setStart;
- (NSDate *)getStart;
#end
#implementation Ash
- (IBAction)startTimer {
self.startNSDate = [NSDate date];
}
- (IBAction)stopTimer{
start = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy"];
// this is where it fails, the reason being that startNSDate isn't retained
// and by this line, it's already dealloc'd, hence you're trying to access
// garbage pointer
NSString *stringFromDate = [formatter self.startNSDate];
NSLog(#"stringfromdate: %#", stringFromDate);
}
- (void)dealloc
{
self.startNSDate = nil;
[super dealloc];
}

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

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.
But I'm getting a (null) value with NSLog.
Method:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [[NSDate alloc] init];
if (type==#"month") {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if (type==#"day") {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
//int setDate = theDate;
[dateFormat release];
return theDate;
}
[now release];
return NULL;
}
Calling the function to get value:
NSString *month = [self getNowDateMonth:#"month"];
NSLog(#"%#", month);
Am I going about this the right way?
First of all, compare the strings using [#"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.
Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].
To sum up, a suggested better version of this method would be:
-(NSString *) getNowDateMonth:(NSString *)type {
NSDate *now = [NSDate date];
if ([#"month" isEqualToString:type]) {
NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
[monthFormat setDateFormat:#"MM"];
NSString *theMonth = [monthFormat stringFromDate:now];
[monthFormat release];
return theMonth;
} else if ([#"day" isEqualToString:type]) {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"dd"];
NSString *theDate = [dateFormat stringFromDate:now];
[dateFormat release];
return theDate;
} else {
return nil;
}
}
Also, there are a few other points that can be taken into consideration to improve this method:
do not use NSString as type; use an enum
do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method
You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.
See Date and Time Programming Guide for Cocoa.
Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.