I have a "Today" button to reset a datePicker to today's date. This works for the current month, but not for other months.
The method is:
- (IBAction)setToday:(id)sender
{
NSLog(#"%s", __FUNCTION__);
[datePicker setDateValue:[NSDate date]];
[datePicker setNeedsDisplay: YES];
}
What am I doing wrong?
I'm assuming your date picker is a property, in which case you should use the self keyword.
self.datePicker.date = [NSDate date];
Related
I have made a custom datePickerView with a done and cancel button.
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
}
return self;
}
-(void)setupWithMinimumDate:(NSDate *)minimumDate andMaximumDate:(NSDate *)maximumDate andTag:(NSInteger)tag{
viewToolbar.backgroundColor = [UIColor toolbarBackgroundColor];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.timeZone = [NSTimeZone localTimeZone];
datePicker.locale = [NSLocale currentLocale];
datePicker.minimumDate = minimumDate;
datePicker.maximumDate = maximumDate;
tagValue = tag;
}
-(IBAction)doneTapped:(id)sender{
[self.delegationListener didTapDone:datePicker.date andTag:tagValue];
}
-(IBAction)cancelTapped:(id)sender{
[self.delegationListener didTapCancel];
}
-(IBAction)datePickerValueChanged:(UIDatePicker *)sender{
NSLog(#"DATE = %#",sender.date);
datePicker.date = sender.date;
}
You see the Log statement in datePickerValueChanged. It gives me back the correct date when I keep inside my minimum and maximum date. But when I scroll above or below my min or max date it always returns me a date which is one day earlier than the date selected.
I know that when I format the date with NSDateFormatter it gives me back the correct Date string. But here is the problem, I store the date that I receive from my datePicker on a Realm object.
Now that realm object I sent to a webserver that needs a dateformatting with UTC timezone. So I always sent a date which is one day earlier.
I hope it's a little bit clear, if not please ask !
as i check your code you are NSLog of NSDate object but NSDate log is not sure to return correct NSDate because NSDate returns current time in GMT time zone so following is the code to do bit calculation of GTM timezone to your local timezone:
-(IBAction)datePickerValueChanged:(UIDatePicker *)sender{
NSTimeZone* GTMTimeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
NSTimeZone* SystemTimeZone = [NSTimeZone systemTimeZone];
NSInteger GTMOffset = [GTMTimeZone secondsFromGMTForDate:sender.date];
NSInteger Systemoffset = [SystemTimeZone secondsFromGMTForDate:sender.date];
NSTimeInterval interval = Systemoffset - GTMOffset;
NSDate* correctDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sender.date];
NSLog(#"DATE = %#",correctDate);
datePicker.date = correctDate;
}
i was implicated in my project from here
Other way is you can convert your NSDate in to string with correct dateformate and nslog it that will be show you correct log like following:
-(IBAction)datePickerValueChanged:(UIDatePicker *)sender{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSLog(#"Todays date is %#",[formatter stringFromDate:sender.date]);
datePicker.date = sender.date;
}
so you can store the date as a string and send it to your backend hope that help to you
How can I fire a UILocalNotification two days before a given NSDate?
Assuming eventDate is the date you have:
NSDate* twoDaysEarlyDate = [[NSDate alloc] initWithTimeInterval:-(86400 * 2) sinceDate:eventDate];
That ignores any possible daylight saving change happening just before the eventDate, which is probably fine for a local notification.
An alternate method if you need to take DST changes into effect would be similar to:
NSCalendar* currentCalendar = [NSCalendar currentCalendar];
NSDateComponents* offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-2];
NSDate* twoDaysEarlyDate = [currentCalendar dateByAddingComponents:offsetComponents toDate:eventDate options:0];
Either option works depending on your needs.
Suppose given date is 'expirationDate' and 'twoDaysBeforeExpirationDate' is the desired date to fire UILocalNotification. Then
NSDate* expirationDate=nil;
NSDate *twoDaysBeforeExpirationDate = [expirationDate dateBySubtractingRequiredDays:2];
- (NSDate *) dateBySubtractingRequiredDays: (NSInteger) dDays
{
return [self dateByAddingDays: (dDays * -1)];
}
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.
I want to make the date to change one day every "n" seconds, like a time machine. I have this code but nothing happens, any help will be appreciated.
this is the code: no issues, no error ... no tomorrow date!
-(IBAction)jumpDate
{
NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
[dateFormater setDateFormat:#"dd MMMM yyyy h:mm:ss"]; //dateFormater.dateStyle =NSDateFormatterLongStyle; //USA date style MMMM-dd-yyyy
[dateFormater setTimeZone:[NSTimeZone timeZoneWithAbbreviation:#"CDT"]];
NSDate *todayDate = [[NSDate alloc]init];
[gregDate setText : [dateFormater stringFromDate:todayDate]];
[NSString stringWithFormat:#"dd MMMM yyyy", dayCount];
dayCount++;
if (dayCount >= 365)
{
dayCount = 365;
[timerDate invalidate];
}
}
//and the timer
- (void)viewDidLoad
{
NSDateFormatter *dateFormater = [[[NSDateFormatter alloc]init]autorelease];
[dateFormater setDateFormat:#"dd MMMM yyyy"];
NSTimeInterval secondsPerDay = 86400 ; // = 24 * 60 * 60
NSDate *today = [[[NSDate alloc]init]autorelease];
NSDate *tomorrow;
tomorrow = [today dateByAddingTimeInterval:(NSTimeInterval)secondsPerDay];
[gregDate setText : [NSString stringWithFormat:#" %# ",tomorrow]];
dayCount = 1;
timerDate=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(jumpDate)userInfo:nil repeats:YES];
[super viewDidLoad];
}
I have 3 questions, not all directly related to your question.
Why -(IBAction)jumpDate is an IBAction, if you are calling this method from your code you should changed it to (void) and if an IBAction need to call that, call it from an other method that would be the action for that button.
Is there a missing space in your code before userInfo in this call :
timerDate=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:#selector(jumpDate)userInfo:nil repeats:YES];
Did you verified that your IBOutlet are all set properly? I've stop counting the times I've forgot that.
[gregDate setText : [NSString stringWithFormat:#" %# ",tomorrow]];
What is gregDate? is it an IBOutlet pointing to a UILabel?
And you've probably verified this, but, that call retunr a valid string?
You should not call your IBAction method from your timer, for 2 reasons,
1. I really think it's bad design, it's introducing confusion on the role of this method since it's also call from a timer.
2. The method signature doesn't match the one NSTimer needs
aSelector:
The message to send to target when the timer fires. The selector must have the following signature:
- (void)timerFireMethod:(NSTimer*)theTimer
This text come from the NSTimer class reference.
Replace this line:
NSDate *todayDate = [[NSDate alloc]init];
with this line:
NSDate *todayDate = [[NSDate date] dateByAddingTimeInterval:dayCount * 86400];
I have a NSDate that I must compare with other two NSDate and I try with NSOrderAscending and NSOrderDescending but if my date is equal at other two dates?
Example: if I have a myDate = 24/05/2011 and other two that are one = 24/05/2011 and two 24/05/2011 what can I use?
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters anotherDate
The date with which to compare the
receiver. This value must not be nil.
If the value is nil, the behavior is
undefined and may change in future
versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are
exactly equal to each other,
NSOrderedSame
The receiver is later in
time than anotherDate,
NSOrderedDescending
The receiver is
earlier in time than anotherDate,
NSOrderedAscending
In other words:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
if ([date2 isEqualToDate:date2]) ...
See Apple Documentation about this one.
After searching, I've got to conclusion that the best way of doing it is like this:
- (BOOL)isEndDateIsSmallerThanCurrent:(NSDate *)checkEndDate
{
NSDate* enddate = checkEndDate;
NSDate* currentdate = [NSDate date];
NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
double secondsInMinute = 60;
NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;
if (secondsBetweenDates == 0)
return YES;
else if (secondsBetweenDates < 0)
return YES;
else
return NO;
}
You can change it to difference between hours also.
If you want to compare date with format of dd/MM/yyyy only, you need to add below lines between NSDate* currentdate = [NSDate date]; && NSTimeInterval distance
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yyyy"];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en_US"]
autorelease]];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
currentdate = [dateFormatter dateFromString:stringDate];
I take it you are asking what the return value is in the comparison function.
If the dates are equal then returning NSOrderedSame
If ascending ( 2nd arg > 1st arg ) return NSOrderedAscending
If descending ( 2nd arg < 1st arg ) return NSOrderedDescending
I don't know exactly if you have asked this but if you only want to compare the date component of a NSDate you have to use NSCalendar and NSDateComponents to remove the time component.
Something like this should work as a category for NSDate:
- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];
NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
return [selfDateOnly compare:otherDateOnly];
}
NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.
NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
* Construct two dates that bracket the day you are checking.
* Use the user's current calendar. I think this takes care of things like daylight saving time.
*/
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
* Compare the date with the start of the day and the end of the day.
*/
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];
if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
// we are on the right date
}
Check the following Function for date comparison first of all create two NSDate objects and pass to the function:
Add the bellow lines of code in viewDidload or according to your scenario.
-(void)testDateComaparFunc{
NSString *getTokon_Time1 = #"2016-05-31 03:19:05 +0000";
NSString *getTokon_Time2 = #"2016-05-31 03:18:05 +0000";
NSDateFormatter *dateFormatter=[NSDateFormatter new];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss Z"];
NSDate *tokonExpireDate1=[dateFormatter dateFromString:getTokon_Time1];
NSDate *tokonExpireDate2=[dateFormatter dateFromString:getTokon_Time2];
BOOL isTokonValid = [self dateComparision:tokonExpireDate1 andDate2:tokonExpireDate2];}
here is the function
-(BOOL)dateComparision:(NSDate*)date1 andDate2:(NSDate*)date2{
BOOL isTokonValid;
if ([date1 compare:date2] == NSOrderedDescending) {
//"date1 is later than date2
isTokonValid = YES;
} else if ([date1 compare:date2] == NSOrderedAscending) {
//date1 is earlier than date2
isTokonValid = NO;
} else {
//dates are the same
isTokonValid = NO;
}
return isTokonValid;}
Simply change the date and test above function :)