Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the most efficient way to obtain an NSDate object that represents midnight of the current day?

like image 385
markdorison Avatar asked Jan 27 '12 21:01

markdorison


2 Answers

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" 
like image 147
Richard Venable Avatar answered Oct 01 '22 17:10

Richard Venable


Try this:

NSDate *const date = NSDate.date; NSCalendar *const calendar = NSCalendar.currentCalendar; NSCalendarUnit const preservedComponents = (NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay); NSDateComponents *const components = [calendar components:preservedComponents fromDate:date]; NSDate *const normalizedDate = [calendar dateFromComponents:components]; 
like image 32
Christian Schnorr Avatar answered Oct 01 '22 17:10

Christian Schnorr