How can I get an NSDate object for today at midnight?

New API in iOS 8

iOS 8 includes a new method on NSCalendar called startOfDayForDate, which is really easy to use:

let startOfToday = NSCalendar.currentCalendar().startOfDayForDate(NSDate())

Apple’s description:

This API returns the first moment date of a given date.
Pass in [NSDate date], for example, if you want the start of “today”.
If there were two midnights, it returns the first. If there was none, it returns the first moment that did exist.

Update, regarding time zones:

Since startOfDayForDate is a method on NSCalendar, it uses the NSCalendar’s time zone. So if I wanted to see what time it was in New York, when today began in Los Angeles, I could do this:

let losAngelesCalendar = NSCalendar.currentCalendar().copy() as! NSCalendar
losAngelesCalendar.timeZone = NSTimeZone(name: "America/Los_Angeles")!

let dateTodayBeganInLosAngeles = losAngelesCalendar.startOfDayForDate(NSDate())
dateTodayBeganInLosAngeles.timeIntervalSince1970

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.timeStyle = .ShortStyle
dateFormatter.timeZone = NSTimeZone(name: "America/New_York")!
let timeInNewYorkWhenTodayBeganInLosAngeles = dateFormatter.stringFromDate(dateTodayBeganInLosAngeles)
print(timeInNewYorkWhenTodayBeganInLosAngeles) // prints "Jul 29, 2015, 3:00 AM"

Leave a Comment