views:

73

answers:

3

I've tried multiple methods and tried some suggestions on this site, but how can I determine if a CoreData attribute "dueDate" is equal to "Today", I know NSDate is a specific time as well but I want the predicate to return if it is the same day/month/year regardless of what the time is in the day. Any suggestions?

A: 

Couple things that you might want to try.

  1. Add another integer attribute, dueDateYYYMMDD to your entity. Convert the NSDate using NSDateFormatter to the YYYYMMDD string, then use NSString integerValue to produce the dueDateYYYYMMDD.
  2. Use NSDateFormatter on [NSDate date] to produce "today" in YYYYMMDD format and [NSString integerValue] to obtain "today" as an integer (todayInt). Now your predicate can be easily constructed to compare dueDateYYYYMMDD == todayInt.

Comparison on integer values is more efficient than strings.

falconcreek
And what if today means within 24 hours? Or the last 24 hours? What about timezones?
Marcus S. Zarra
Fair question. A day is an imprecise measurement of time. comparisons are only useful when using the same unit of measurement; be it time, money, mass or volume.
falconcreek
A: 

The concept of today is tricky because what do you mean by it? That is why it is not straightforward. Do you mean as in the same day, month and year regardless of timezone? Do you mean within the same 24 hour period? Within the last 24 hours? It can get complicated.

Your answer to the above determines the answer to your question. If it is the same day, month and year then use NSDateComponents to extract those three values and compare them. If you mean within 24 hours then you can use the date method -timeIntervalSinceDate: to determine the number of seconds between the dates.

If you mean something else then please clarify.

Marcus S. Zarra
+2  A: 

Fixed this by using NSDateComonents and NSCalendar.

Just created NSDateComponents of just day/month/year from the original NSDate and then re-created it to a date using dateFromComponents.

This lead to it being the start of the day, I then created another date using the method above that was the start of "tomorrow" and used > and < to see if it was "today." Thanks for the help anyway.

Jamie Maddocks
+1 this is how I would've done it
Dave DeLong
This effectively does the same as using using NSDateFormatter which is also locale aware. In either solution, enable the "Indexed" flag on the "dueDate" attribute to help avoid testing all of the Entities against the predicate. (more important as the number of managed objects if you are dealing with increases)
falconcreek