comparing Two NSDate objects not working - objective-c

I'm learning about how to compare NSDate objects with the isEqualToDateDate method. I don't get why this simple test does not return true and print out the NSLog. Thanks in advance
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSDate *myDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSDate *otherDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSLog(#"myDate %#",myDate);
NSLog(#"otherDate %#",otherDate);
if ([myDate isEqualToDate:otherDate]) {
NSLog(#"The dates are the same");
};
[myDate release];
[otherDate release];
[pool drain];
return 0;
}

I believe, and this may be wrong, that since you are using initWithTimeIntervalSinceNow that the objects are being allocated at slightly different times, thus making them unequal.

Both dates are indeed slightly different. Quick example to show the difference:
NSDate *one = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSComparisonResult difference = [two compare:one];
NSLog(#"Date one: %#",one);
NSLog(#"Date two: %#",two);
NSLog(#"Exact difference: %ld",difference);
Output:
Date one: 2012-01-03 07:47:40 +0000
Date two: 2012-01-03 07:47:40 +0000
Exact difference: 1
EDIT
isEqualToDate: returns true in the following example:
NSDate *one = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
if ([one isEqualToDate:two]) NSLog(#"Equal");
Output:
Equal

Related

Segmentation Error In Objective C

I am trying to write a program for NSDate in ubuntu (as I don't have mac so I am using Ubuntu to run my objective c programs).
While compiling the program I am getting an error "Segmentation fault (core dumped)".
Below is my code
#import <Foundation/Foundation.h>
#import <objc/objc.h>
#import <objc/Object.h>
int main()
{
NSAutoreleasePool * pool=[[NSAutoreleasePool alloc] init];
NSDate *now = [NSDate date];
NSLog(#"now %#", now);
NSTimeInterval secondsInAWeek = 7 * 24 * 60 * 60;
NSLog(#"secondsInAWeek %#", secondsInAWeek);
NSDate *lastWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
NSLog(#"last week %#", lastWeek);
NSDate *nextWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
NSLog(#"next week %#", nextWeek);
[pool drain];
return 0;
}
Please help me to find the error. I am able to get the output for NSDate *now, but after that i am getting the segmentation error.
Ask me if you need any more info regarding the code.
I guess I am able to get a solution to my answer. I was trying different things and this solution worked but still I don't know how it did.
#import <Foundation/Foundation.h>
#import <objc/objc.h>
#import <objc/Object.h>
int main()
{
NSAutoreleasePool * pool=[[NSAutoreleasePool alloc] init];
NSDate *now = [NSDate date];
NSLog(#"now %#", now);
NSTimeInterval secondsInAWeek = 7 * 24 * 60 * 60;
NSLog(#"secondsInAWeek %f", secondsInAWeek);
NSDate* lastWeek = [[[NSDate alloc] initWithTimeInterval:-secondsInAWeek sinceDate:now] autorelease];
NSLog(#"last week %#", lastWeek);
NSDate *nextWeek = [[[NSDate alloc] initWithTimeInterval:secondsInAWeek sinceDate:now] autorelease];
NSLog(#"next week %#", nextWeek);
[pool drain];
return 0;
}
I have changed
NSDate *lastWeek = [NSDate dateWithTimeInterval: secondsInAWeek
sinceDate:now];
with
NSDate *lastWeek = [[[NSDate alloc]
initWithTimeInterval:secondsInAWeek sinceDate:now] autorelease];
Its working fine and giving the desired output.
I still don't know why and how it worked. :)

How do you compare date objects to strings in Objective-C?

I have an array of dates in this format:
date: 2012-01-02,2012-03-17,2012-04-09,2012-05-07,2012-06-04,2012-08-06,2012-10-29,2012-12-25,2012-12-26.
I want to compare the dates with today's date, but I need some help. This is my code.
NSArray *date =[dict12 objectForKey:#"ie_date_closed"];
NSLog(#"date:%#",date);
int i=date;
for (i=0; i<6; i++)
{
NSComparisonResult result = [todaydate compare:date[i]];
NSLog(#"result:%d",result);
}
Try below code:-
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy-MM-dd"];
for (NSString *arrDt in date){
if ([arrDt isEqualToString:[formatter stringFromDate:[NSDate date]]]){
NSLog(#"Equal Date");}}
Note:- You need to set the dateFormat according to array object dates.
Here is the code have a look at & try to implement your self using it :
for (i=0; i<[date count]; i++)
{
NSDateformatter *format = Define Your date Format Here
NSDate yourDate = [format dateFromString:[date objectAtIndex:i]];
If ([YourDate compare:[NSDate date]] == NSOrderedSame)
{
NSLog(#"Both Dates are same");
}
}
Note : I am not giving you whole readymade code but just for a hint so using it you can be able to implement what you want.
Hope this will help.
try it
NSDate *firstTime;
NSDate *nowTime;
NSDate *localDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter.dateFormat = #"YYYY-MM-dd";
NSString *str = [dateFormatter stringFromDate:localDate];
NSArray *date =[dict12 objectForKey:#"ie_date_closed"];
NSLog(#"date:%#",date);
for (i=0; i<[date count]; i++)
{
NSString *openTime =[NSString stringWithFormate:"%#"[date objectAtindex:i]];
NSDateFormatter *dateComperFormatter1 = [[NSDateFormatter alloc] init];
[dateComperFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];
[dateComperFormatter1 setDateFormat:#"YYYY-MM-dd"];
firstTime = [dateComperFormatter1 dateFromString:openTime];
nowTime = [dateComperFormatter1 dateFromString:str];
// NSComparisonResult result;
// // has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
//
// result = [nowTime compare:firstTime]; // comparing two dates
NSComparisonResult result = [nowTime compare:firstTime];
}

NSString to NSDate is NOT working when called multiple times

I have written this function in a class:
- (NSDate *) convertDate : (NSString *) dateStr{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *dateFrmStr = [[NSDate alloc] init];
dateFrmStr = [dateFormatter dateFromString:dateStr];
return dateFrmStr;
}
I am calling this function in another class like this:
NSString * dateStr1 =#"01-01-1977";
NSString * dateStr2 =#"22-12-1977";
NSString * dateStr3 =#"19-01-1978";
MyClass *data = [[MyClass alloc]init];
NSDate *dateObj1 = [data convertDate:dateStr1];
NSDate *dateObj2 = [data convertDate:dateStr2];
NSDate *dateObj3 = [data convertDate:dateStr3];
NSLog(#" >>> dateObj1 %#",dateObj1);
NSLog(#" >>> dateObj2 %#",dateObj2);
NSLog(#" >>> dateObj3 %#",dateObj3);
When I run this the only first date seems to get converted because the output I get is :
>>> dateObj1 1977-01-01 00:00:00 +0000
There is no error nothing but the programs just stops.
I've tried you're code and for me works very fine( with ARC ), probably you're issue is somewhere else in "MyClass"…
BTW! Why don't you make a "category" on NSDate?
Something like this :
NSDate + ConvertDate.h
#interface NSDate (ConvertDate)
+(NSDate *) convertDateFromString : (NSString *)dateString;
#end
NSDate + ConvertDate.m
#implementation NSDate (ConvertDate)
+(NSDate *)convertDateFromString:(NSString *)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd-MM-yyyy"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
return [dateFormatter dateFromString:dateString];
}
#end
Yes it looks like your code, the only differences are that you don't need to allocate an instance of "MyClass" to use the
"convertDateFromString" method because you're using a class method.'
could it be
NSString * dateStr2 =#"22-12-1977";
that NSDate thinks 22 as the month??? maybe try 12-22-1977 instead?? i usually use NSDateFormatter to convert to string or date..

Using NSDate in While loop

I want to get the current date using [NSDate date] in a While Loop. I accomplish this by doing like this:
while (interval > 0.0) {
NSDate *currentDate = [[NSDate alloc] init];
currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
[currentDate release];
}
I dont know why is the Memory leaks shows that there is a great amount of memory is leaked. Kindly guide me that what is the right way to accomplish my task.
In line NSDate *currentDate = [[NSDate alloc] init]; you create a new object, which you should release. In line currentDate = [NSDate date]; you do not release an old object, you only make a pointer to point to another object. In line [currentDate release]; you release an object created on the second line of a loop, which may cause an error (that object is marked as autorelease one and iOS will clean it for you). You should rewrite your code like:
while (interval > 0.0) {
NSDate *currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
}
You don't need the first line NSDate *currentDate = [[NSDate alloc] init];. You can directly assign the [NSDate date] to currentDate.
NSDate *currentDate = nil;
while (interval > 0.0) {
currentDate = [NSDate date];
interval = (float) [newDate timeIntervalSinceDate: currentDate] / 60;
}
The problem is not that you are leaking per se but that you are running in a while loop.
The auto released dates are growing in the autorelease pool because the pool only empties in the idle time on the run loop.
One solution is to create a local autorelease pool within the scope of the while
while (foo) {
NSAutoreleasePool *aPool = [[NSAutoreleasePool alloc ] init];
NSDate *currentDate = [NSDate date];
// other computational foo
[aPool release]
}
When you release the pool in the local scope it will immediately drop the autoreleased date you requested.

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.