How to query for 'task' records by date - ios

We are trying to make a app that keeps a users schedule. He wants a simple tableview to display a different section for each day and he wants all the tasks for that day to display in order. Here is the db schema im using:
TASK_ID , TASK_NAME(STRING), TASK_DURRATION(AMOUNT OF TIME IN MILI), TASK_START_TSTAMP(EPOCH TIMESTAMP), TASK_END_TSTAMP(EPOCH TIMESTAMP), TASK_COMPLETED(BOOL)
How would I begin to go about querying for tasks by day? Like if i wanted to return all the tasks for the next 7 days.
I have to :
•Allow users to create tasks with a specific duration and in some cases a specific start time
•Query for the next 7 days worth of tasks chunked by date.
So what do I do? Find a way to get a array of the next 7 days, loop through and run a query for each one for all the tasks scheduled on that day?

You want to calculate startDate and endDate to be used in your SQL using calendrical calculations of NSCalendar.
Let's say it's 3:24pm on January 20th, and you want all tasks in the next seven days, up to 3:24pm on January 27th, you could do something like:
let startDate = NSDate()
let endDate = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 7, toDate: startDate, options: [])!
Then build your query using those start and end dates.
If, however, you want all events scheduled anytime on January 20th through January 26th (inclusive), you could use something like:
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Month, .Year], fromDate: NSDate())
let startDate = calendar.dateFromComponents(components)!
let endDate = calendar.dateByAddingUnit(.Day, value: 7, toDate: startDate, options: [])!
Then you could build your SQL using startDate and endDate, if you're storing those as UNIX epoch double values:
let sql = "select * from TASKS where TASK_START_TSTAMP >= \(startDate.timeIntervalSince1970) and TASK_START_TSTAMP < \(endDate.timeIntervalSince1970)"

Related

Trying to return ONLY tomorrow's data using Swift and Core Data but it returns both today's and tomorrow's together?

I am trying to return ONLY tomorrow's data using Swift and Core Data but it returns both today's and tomorrow's together. Any idea why? Below is the code I am using. Thank you in advance!
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: []
)
todoTomorrow = CoreDataManager.getData("ToDos", predicate: NSPredicate(format:"dueDate<%#", ((tomorrow))!)) as! [ToDos]
You need to modify your predicate to be dueDate < %# AND dueDate > %# with parameters tomorrow and today so it checks both the upper and lower allowed range of the dates.

Swift Core Data Fetch results from a certain date

I'm fairly new to ioS dev so this might be obvious.
With Core Data, I have an Entity : 'Post' , with an attribute for "dateAdded".
When the user selects an NSDate on a calendar- I want to fetch all the entries on that day only and load that into a table.
I was thinking of using a predicate where dateAdded (NSDate) would be equal to the calendarSelectedNSDate. But I don't think that would work as their NSDates would be different because of different times.
I would really appreciate a solution! Thank you!
Use (NS)Calendar to calculate the start and end of the selected date and create a predicate:
// get the current calendar
let calendar = Calendar.current
// get the start of the day of the selected date
let startDate = calendar.startOfDay(for: calendarSelectedNSDate)
// get the start of the day after the selected date
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate, options: .matchNextTime)!
// create a predicate to filter between start date and end date
let predicate = NSPredicate(format: "dateAdded >= %# AND dateAdded < %#", startDate as NSDate, endDate as NSDate)

Get dats from week number of particular year

I need one function where i will pass any week number and year, that function should return dates for that week. Like if I pass week 2 and year 2016 then function should return me 3 January to 9 January.
Just a very simple solution using NSCalendar functionality:
let week = NSDateComponents()
week.yearForWeekOfYear = 2016 // the year
week.weekOfYear = 10 // week index
let calendar = NSCalendar.currentCalendar()
// start of week or nil if the week does not exist
let weekStart = calendar.dateFromComponents(week)
// add 1 week to start (this is essentially the start of the next week)
let weekEnd = calendar.dateByAddingUnit(.WeekOfYear, value: 1, toDate: weekStart!, options: [])
print(weekStart)
print(weekEnd)

Neat way to get end of day for date?

I am querying a database for values between a startDate and an endDate. I am therefore looking for a neat way to get the NSDate for the end of the day for a date. Just like you can get startOfDayForDate().
I guess you could do :
let cal = NSCalendar.currentCalendar()
let startOfDay = cal.startOfDayForDate(NSDate())
let aDay:NSTimeInterval = 60*60*23 + 60*59 + 59
let endofDay = startOfDay.dateByAddingTimeInterval(aDay)
Is adding component.day + 1 to startOfDayForDate the correct method to get the "end of the day" for a date, or is there a better method?
A better way would be to get the start of the next day and subtract 0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001 second.
Do you get what I want to say? It's very hard to define the end of the day. 23:59 is certainly not the end of the day, there is almost a whole minute left until the next day. And even 23:59:59 is not the end of a day. Because there is an infinite amount of fraction seconds between this time and the start of the next day. As far as I know NSDate supports nanoseconds out of the box, so in the current implementation there are at least 1 000 000 000 possible NSDates between 23:59:59 and the next day.
That's why you should see if you can find a way to use the start of the next day.
For example, instead of if (startOfDay <= date && date <= endOfDay) you could use if (startOfDay <= date && date < startOfNextDay).
To calculate the start of the next day you have to use NSCalendar. In iOS8 Apple added a couple of nice methods to make these calculations short:
let calendar = NSCalendar.currentCalendar()
let startOfDay = calendar.startOfDayForDate(NSDate())
let startOfNextDay = calendar.dateByAddingUnit(.CalendarUnitDay, value: 1, toDate: startOfDay, options: nil)!
EDIT: Since you now state that you want to query a database you don't need to find the end of the day. Check if the date is on or after the start of the day, and before the start of the next day.
Try this:
var endOfDay: Date? {
var components = DateComponents()
components.day = 1
components.second = -1
var calendar = Calendar.current
calendar.timeZone = TimeZone(abbreviation: "GMT")!
return calendar.date(bySettingHour: 11, minute: 59, second: 59, of: Date())
}

To query yesterday records from the Parse table using Swift

I'm going to develop the piece of code to query all the records created yesterday. Well I know it's something very trial. Nevertheless it's one million question for me right now because I'm novice in programming. Below the SWIFT code that doesn't work properly though. For backend I use Parse.com.
var yesterday = NSDate() - 1.day.ago // 1.day.ago isn't valid but what I need.
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", equalTo:"yesterday")
Help please! As always sooner you help higher your chances to win the Tesla Model S Lottery! :)
You can use a pretty cool new attribute of NSCalendar called dateByAddingUnit to easily get yesterday's date:
let today = NSDate()
let yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay,
value: -1,
toDate: today,
options: NSCalendarOptions(0))
Where you set .CalendarUnitDay as the calendar unit you wish to add/subtract by and the value of -1 to indicate the change you want for that calendar unit.
But the problem with your query is that it specifically requests that a PFObject's "createdAt" date equals a specific time, not that the PFObject was created at anytime during that day. So I suggest you create two constraints in your query -- a greater than and a less than between midnight (the start of the day) yesterday and midnight (the start of the day) today so that the query will return all the results in between.
Update:
To get the start of yesterday and today, i.e. midnight, (converted to GMT to match the dates in the parse database, though that line can be removed if that's not your intent) here's what you can do:
var today = NSDate()
let calendar = NSCalendar.autoupdatingCurrentCalendar()
calendar.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let preservedComponents = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit
today = calendar.dateFromComponents(calendar.components(preservedComponents, fromDate: today))!
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: -1, toDate: today, options: NSCalendarOptions(0))
Then to perform your query:
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", greaterThanOrEqualTo: yesterday)
query.whereKey("createdAt", lessThan: today)
import UIKit
extension NSDate {
func xDays(x:Int) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: x, toDate: self, options: [])!
}
}
let today = NSDate()
let yesterday = NSDate().xDays(-1)
let dayBeforeYesterday = NSDate().xDays(-2)
Try this:
var yesterday = NSDate.date() - 1.days
var query = PFQuery(className:"score") // table name is score
query.whereKey("createdAt", equalTo:yesterday)
Pay attention at equalTo:yesterday without quotes
Simply try below code. It works fine in iOS7 and iOS8
let today = NSDate()
let tomorrow = today.dateByAddingTimeInterval(24 * 60 * 60)
let yesterday = today.dateByAddingTimeInterval(-24 * 60 * 60)

Resources