So i am making an app that counts how many Calories/protein etc you eat each day and then you can compare after lets say 1 week how much you ate at average day. Everything is working perfect its just that it counts from the exact time you start the session to the exact time when you check the overall statistic. Here i will show some code i use for this function to work:
here is the code to save the start date on the first View:
let currentDate = NSDate()
let defaults5 = NSUserDefaults.standardUserDefaults()
defaults5.setObject(currentDate, forKey: "startDay")
Here is the code to check the end date and compare the dates to see how many days it has passed(this is on another view):
let currentDate = NSDate()
var startDay = NSDate()
var totalDays = Int()
let defaults1 = NSUserDefaults.standardUserDefaults()
if let search1 = defaults1.objectForKey("startDay")
{
startDay = search1 as! NSDate
}else{
print("there is no start date")
}
func daysBetweenDate(startDate: NSDate, endDate: NSDate) -> Int
{
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
return components.day
}
totalDays = daysBetweenDate(startDay, endDate: currentDate) + 1
dayLabel.text = String(totalDays)
So in this case the DayLabel will show how many days it is between start day and currentDate (+1) but i want this ignore hours for example if i start the session 16.00 on Tuesday and i check 15.00 on Wednesday it will still count as 0 days because it has only passed 23 hours, i would want it to start the startDay at 00.00 every time.