Reputation: 8951
I have looked through a few similar questions on here, but they address slightly different issues than what I'm trying to do. I want to create an NSDate
object for the beginning and end of yesterday (12:00am - 12:00am). I have successfully created an NSDate
for the start of the day and the end of the day, but I can only do it for the current day, not the previous day. This doesn't seem like it should be much more difficult, but I've run into some trouble with it.
My start and end NSDate
for the current day:
extension NSDate {
var startOfDay: NSDate {
return NSCalendar.currentCalendar().startOfDayForDate(self)
}
var endOfDay: NSDate? {
let components = NSDateComponents()
components.day = 1
components.second = -1
return NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions())
}
}
I've tried adding something like this:
var yesterday = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: -1, toDate: NSDate(), options: nil)
But I get an error
Type of expression is ambiguous without more context
. I'm clearly missing something important here, but I can't seem to figure out what it is.
Upvotes: 0
Views: 810
Reputation: 22252
Some extensions I drag around. Plop the following in a play and enjoy:
import UIKit
extension NSDate {
var yesterday:NSDate {
let calendar = NSCalendar.currentCalendar()
return calendar.startOfDayForDate(calendar.dateByAddingUnit(.Day, value: -1, toDate: self, options: NSCalendarOptions.WrapComponents)!)
}
var tomorrow:NSDate {
let calendar = NSCalendar.currentCalendar()
return calendar.startOfDayForDate(calendar.dateByAddingUnit(.Day, value: 1, toDate: self, options: NSCalendarOptions.WrapComponents)!)
}
}
let now = NSDate()
now.yesterday
now.tomorrow
now.yesterday.yesterday.yesterday.yesterday
now.tomorrow.yesterday
Upvotes: 1