NSDate compare is false? [duplicate] - objective-c

This question already has answers here:
NSDate isEqualToDate: not working - does it look at seconds and split seconds?
(3 answers)
Closed 8 years ago.
i compare 2 NSDates which are the same and i get false result.
i cant show how i get this dates because its too long , but i can show what i do :
NSLog(#"this date is:%# , and date we check to equality is:%#",thisDate,dateToFind);
if([thisDate isEqualToDate:dateToFind] )
{
NSLog(#"equal date!"); // not printed!
}
the NSLog show me this :
this date is:2012-09-13 14:23:54 +0000 , and date we check to equality is:2012-09-13 14:23:54 +0000
he doesnt print the NSLog .
why ?

As a few have said it seems to be the fractions of a second that are giving you trouble. The reason for this is that an NSDate is simply an object wrapper around an NSTimeInterval(double) with a value in seconds since the reference date(12AM January 1 2001 GMT).
There are a couple main ways to deal with this. Either check the date to see if it is in a given range, or (more likely based on your question) truncate the fractions of a second completely off.
Truncating seconds from an NSDate is trivial code. You may want to truncate all of the dates that you are storing as you store them for quick comparisons. You can truncate an existing NSDate like this:
NSDate *truncatedDate = [NSDate dateWithTimeIntervalSinceReferenceDate:((NSTimeInterval)lround(originalDateObject.timeIntervalSinceReferenceDate))];
This code is pretty self explanatory. It grabs the date's backing time interval rounds it to an integer casts that back to a time interval and creates a new truncated date.
Once you do this to both dates you can then compare your two truncated dates and they will behave as expected.
Or if you must do something without changing your date data you could simply do:
if (lround(thisDate.timeIntervalSinceReferenceDate) == lround(dateToFind.timeIntervalSinceReferenceDate)){
// If whole seconds are equal, as shown in log, this will execute.
}

NSLog(#"this date is:%# , and date we check to equality is:%#",
thisDate,dateToFind);
Try changing the above with:
NSLog(#"this date is:%f , and date we check to equality is:%f",
[thisDate timeIntervalSince1970],
[dateToFind timeIntervalSince1970]);

Related

Fetch objects from Coredata using NSDate

I have 10 records in database. I want to fetch the record where date == mydate.
For eg, there are 2 records in database, which has date of 502479617.512 (in milliseconds).
I am converting the above date to NSDate using
[NSDate dateWithTimeIntervalSinceReferenceDate:502479617.512].
I am getting 2016-12-03 17:40:17 +0000
I have date parameter '502479617.500' which returns same NSDate 2016-12-03 17:40:17 +0000.
But when i try to fetch from coredata, i am getting 0 objects. It is because of milliseconds in the database. How can i discard milliseconds to fetch the records which has same date, time and seconds.
NSDate properties will be stored as NSDate attributes, unless the "Use scalar properties for primitive data types" checkbox is marked.
In that case, the core data attribute will be stored as a NSTimeInterval (double).
You can do it in either of two ways:
First, you could eliminate the seconds decimals when storing the NSDate. It could be automated by overriding didSet for the property. You could also simply do it wherever you do the conversion you describe.
Alternatively, you could specify an interval of one second when fetching. Your fetch request would then need a predicate of this kind:
NSPredicate(format: "date >= %# && date < %#", aDate, aDate.addingTimeInterval(60))
Objective-C
[NSPredicate predicateWithFormat:#"date >= %# && date < %#",
aDate, [aDate dateByAddingTimeInterval:60]];
Just save it as NSString. Then convert back to double when you need it.

Backendless filter results based on current date

I have this query
https://api.backendless.com/v1/data/abc?pageSize=100&loadRelations=cinema&sortBy=showing%20asc&where=objectId%3D%272C225111-18FC-DD4F-FF40-E227F49F5B00%27%20AND%20showing%20%3E%20%2714-June-2016%27
Thi query rightly fetches all the results after the date 14 June 2016. But I am giving a hard coded date here, Is there any way I can simply add current time/date here so that It brings all the results prior to current time? I am looking for something like
https://api.backendless.com/v1/data/abc?pageSize=100&loadRelations=cinema&sortBy=showing%20asc&where=objectId%3D%272C225111-18FC-DD4F-FF40-E227F49F5B00%27%20AND%20showing%20%3E%20%CURRENT TIME%27
I have searched alot, and even the documentation refers to hardcode dates or millisecond format only. Any help is appreciated
The easiest option is just to use the UNIX timestamp version of the date, so the string to use in your where clause would be like:
NSString *where = [NSString stringWithFormat:#"showing < %#", [[NSDate date] timeIntervalSince1970]];

Comparing dates [duplicate]

This question already has an answer here:
Comparing dates [duplicate]
Know if a date(weekday) is bettween two other dates(weekedaysÂș)
(1 answer)
Closed 9 years ago.
In my application I need to compare three dates in one if-else cycle. I have a start date, end date and the date of testing. What I want to check is whether the test date is between the start date and end date.
if (testDate >= startDate && testDate <= endDate) {
If I set the startDate to 25/04/2012 and the endDate to 24/04/2019 and the testDate to 25/12/2013 the code works. But if i set the startDate to 26/04/2000 and the endDate to 24/04/2019 and the testDate to 25/12/2013 the code does not works. What's wrong?
You cannot sanely compare Objective-C objects with any boolean operators in C. You'd be comparing their addresses, not their values.
Look at the documentation for the NSDate class, specifically the -compare: method.
Dates can be compared like that. However, you must first call timeIntervalSince1970 to convert the date to an integer type value. In this case, it gives you a numeric value of type NSTimeInterval.
The other option is to use the compare: method invoked on the NSDate object.
In that case, comparing one date to another will give a result detailed in the class reference as follows:
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.

Current date, convert to multiple timezones, then each needs to check if it is close to another date

I have a project that I need to get the current date/time. From that date/time I need to convert to 6 different timezone's date/time. That is no problem converting the times.
Then from each of the converted date/time I need to see if that date is between two other dates that change every week. I am guessing the times that change everyweek could be an array of dates. The current date/time in that timezone needs to find out which date/time in the array it needs to check itself against. The nearest before and the nearest after. This sounds very confusing just typing this.
Any help pointing me in the right direction would be extremely helpful.
Thankyou
NSDate *date1;
NSDate *date2;
NSDate *date3;
NSTimeInterval firstTimeInterval = [date1 timeIntervalSince1970];
NSTimeInterval secondTimeInterval = [date2 timeIntervalSince1970];
NSTimeInterval thirdTimeInterval = [date3 timeIntervalSince1970];
if (firstTimeInterval<secondTimeInterval && secondTimeInterval<thirdTimeInterval) {
// date2 > date1 and date2 < date3
}
Of course, in my case it would crash since dates have no addresses, but it's just an example... Yours would need to have actual dates in them.
To check if a date is in a specified range just get the unix timestamps and compare them directly like so:
NSDate *lowerLimit = ...
NSDate *upperLimit = ...
NSDate *myDate = ...
BOOL inRange = (lowerLimit.timeIntervalSince1970 <= myDate.timeIntervalSince1970) &&
(upperLimit.timeIntervalSince1970 >= myDate.timeIntervalSince1970);
You could also use NSDate's -compare: method, but I think it's more natural to compare the timestamps.

Comparison of Date/Time with unknown format

I have to time value in output
First is :=
"updated_time" = 1308318422; (Unix timestamp, returning from "stream" table from facebook)
Second is :=
"created_at" = "Thu Jul 14 15:24:51 +0000 2011"; ( This is time of Twitter post, I don't what type of format it is).
I have to compare both date/time. I have to list most recent will come first and so on.
What is the logic? Code preference will be appreciate :)
Thanks in advance
Convert both values to NSDate objects and then use the compare: method.
The first can be converted by getting the int value of the updated_time and then using [NSDate dateWithTimeIntervalSince1970:updatedTimeInt].
The second can be converted with an NSDateFormatter object.