This question already has answers here:
How to compare two dates in Objective-C
(14 answers)
Closed 9 years ago.
Is date1 == date2 not a valid way to compare? If not, what is the correct alternative?
Here's my code:
- (NSDate*) dateWithNoTime {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:self];
NSDate* dateOnly = [calendar dateFromComponents:components];
return dateOnly;
}
- (BOOL) sameDayAsDate:(NSDate*)dateToCompare {
NSDate *date1 = [self dateWithNoTime];
NSDate *date2 = [dateToCompare dateWithNoTime];
return date1 == date2; // HERE IS WHERE THINGS SEEM TO FAIL
}
You're comparing two pointer values. You need to use the NSDate comparison method like:
return ([date1 compare:date2] == NSOrderedSame);
As in the C language (of which Objective-C is a superset), the == (equality) operator compares two pointer values to see if they are equivalent (i.e. if two variables hold the same object). While this works in comparing primitive values (ints, chars, bools), it does not work on Objective-C objects, which might be equal in content, but differ in memory location (which is what the equality operator compares).
To check if two objects are equal, NSObject offers an -isEqual: method which you can use as a general statement (e.g. [date1 isEqual:date2]), and some classes choose to offer a more specific comparison method, such as -isEqualToDate: used to compare NSDates, or -isEqualToString: used to compare NSStrings. These methods cannot be used to compare primitive types (ints, for instance) because those are not objects, but will work on almost all objects.
You can't use == in Objective-C to compare object equality (it will take the C meaning, comparing pointers). Like other languages, you are simply comparing the object pointers.
The message you want is isEqualToDate:, aka [date1 isEqualToDate:date2]
Related
I've two NSDates, one stamped by the devise, and the other entered by the user. I'd like to see if there is a difference between the two, and researched the following code, but I get an error message that NSDate is not identical to NSTimeInterval.
let compareResult = recordDateTimeEntered!.compare(recordDateTimeEntered!)
let timeFromEnteredtoStampedDates = recordDateTimeStamped.timeIntervalSinceReferenceDate(recordDateTimeEntered) // error: NSDate -> _ is not identical to NSTimeInterval
To compare two dates for equality, you can use the == operator in Swift (or the isEqualToDate: method in Objective-C). You can alternatively check that the timeIntervalSinceDate: between two dates is less than an acceptable threshold, to determine if two dates are roughly equal.
I have a core data table view and I am comparing dates. The method which I currently use is: if ([todayDate compare: [NSDate date]]==NSOrderedAscending) . This works perfectly but slow. I do not need to know the difference in time though. Any help is much appreciated!
I really think, that NSDates method isEqualToDate: is what you are searching for. Seems to me to be the Apple-way to answer your question:
NSDate *date1 = ...;
NSDate *date2 = ...;
BOOL datesAreEqual = [date1 isEqualToDate:date2];
For more information visit https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdate_Class/Reference/Reference.html
One option could be to not actually create a new NSDate object but use the time interval for comparison. Don't know about the performance, but it might be worth a try.
if ([todayDate timeIntervalSinceReferenceDate] > [NSDate timeIntervalSinceReferenceDate]) {
...
}
You should remember the current date or current timestamp in a local variable:
NSTimeInterval current = [NSDate timeIntervalSinceReferenceDate];
And use this value later for all your comparisons:
myTimestamp = [myDate timeIntervalSinceReferenceDate]
if (myTimestamp == current) {
return NSOrderedSame;
} else if (myTimestamp > current) {
return NSOrderedDescending;
} else {
return NSOrderedAscending;
}
Or a faster way, using C functions:
// Get the current calendar time as a time_t object.
time_t time ( time_t * timer );
// Return difference between two times
double difftime ( time_t time2, time_t time1 );
I've not measured it, but you may want to try:
NSTimeInterval i = [todayDate timeIntervalSinceNow];
where the result (i) may be positive or negative.
You might also try CFDateCompare.
Or you might want to consider another way to represent a point in time in your database -- such as a CFTimeInterval (a double representing the number of seconds from a common reference time).
i faced a lot of problem while comparing two NSDate with different format though i am new to this.
-what should be the best approach to this problem?
1.I tried to convert this two dates in into one format and then go for comparison
or Should i first Know the format of this two date then go for comparison
NSDate does not know any thing about it's format. Internally the date is stored without any format or region.
To compare date you can use the compare: method.
if([someDate compare:ortherDate] == NSOrderedDescending ){
// someDate later then otherDate;
}
What do you mean with format? After you initialized the NSDate object, you can directly comapre it to any other object of that type like that: (assuming that date1 is of type NSDate)
if ([date1 compare:[NSDate date]] == NSOrderedAscending) {
...
}
You can see the ref here (look for the compare method): https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsdate_Class/Reference/Reference.html
Is there a quick way in Objective-C of identifying NSDate's in an NSArray that have a time of day after a given time (e.g. 8pm)?
I can't quite see anyway other than manually walking through each NSDate in the array and then using NSDateComponents to break out the hour/minute/second...Not even sure if there is a simple way to get the time from an NSDate in a fashion that represents a fraction of 24hours, as this might help a little. (e.g. 6pm would be 18/24 = 0.75 in this case)
There is no need to break in NSDateComponents.
NSTimeInterval interval = [date1 timeIntervalSinceDate:date2];
if (interval > 0) {
// date2 is earlier
} else {
// date1 is earlier
}
Now you can represent your target time(8 P.M., for example) with date2 and compare all dates of array with that.
Haven't tried this myself, but I guess
- (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate
is what you're looking for.
My class needs two properties: startTime and endTime. What is the best class to use? I know there is NSDate, but I only need to store a specific time (something in between 00:00-23:59), I don't need a date. What is the most elegant solution here?
NSTimeInterval is probably good enough for this.
It stores a time value in seconds as a double.
Eg. 5 mins = 300.0
I believe the most elegant solution, and what you want, is NSTimeInterval, that is the primitive type that NSDate is built on top.
NSTimeInterval is a typedef for double, and is a measurement of time in seconds. This primitive time type do not have any concept of a reference date. What NSDate do is to add this concept of reference date and anchor the 0.0 time at 1 January 2001 GMT. There is nothing that stops you from inventing your own reference date or anchor, like for example "midnight of whatever day there is".
What you can do is to add two properties of the NSTimeInterval either as startTime and endTime and let them both use midnight as the reference. Or you could skip endTime and go for a startTime and duration combo.
There's NSDateComponents, which "can also be used to specify a duration of time, for example, 5 hours and 16 minutes."
The NSDate class is similar to the DateTime class in C#: both hold a date and time, but they can be independent of each other. In Cocoa, you would compare two NSDate classes:
//Create NSDate objects in the time format
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"HH:mm:ss"];
NSString *startTimeString = #"00:00:00"; //0 seconds
NSString *endTimeString = #"00:00:52"; //52 seconds
NSDate *startTime = [dateFormatter dateFromString:startTimeString];
NSDate *endTime = [dateFormatter dateFromString:endTimeString];
//Compare the time
BOOL date1before2 = [startTime compare:endTime] == NSOrderedAscending;