如何在ios中获取今天的开始和结束时间?

我通过使用此代码获取当前的date和时间

let today: NSDate = NSDate() let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.MediumStyle dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" dateFormatter.timeZone = NSTimeZone(abbreviation: "SGT"); print(dateFormatter.stringFromDate(today)) 

但我想获得今天的开始时间和结束时间

例如: 12-09-2016 00:00:00 AND 12-09-2016 23:59:59

如何获得当前date的开始和结束时间?

您可以使用startOfDayForDate获取今天的午夜date,然后从该date开始计算结束时间。

 //For Start Date let calendar = NSCalendar.currentCalendar() calendar.timeZone = NSTimeZone(abbreviation: "UTC")! //OR NSTimeZone.localTimeZone() let dateAtMidnight = calendar.startOfDayForDate(NSDate()) //For End Date let components = NSDateComponents() components.day = 1 components.second = -1 let dateAtEnd = calendar.dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions()) print(dateAtMidnight) print(dateAtEnd) 

编辑:将date转换为string

 let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone (abbreviation: "UTC")! // OR NSTimeZone.localTimeZone() dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss" let startDateStr = dateFormatter.stringFromDate(dateAtMidnight) let endDateStr = dateFormatter.stringFromDate(dateAtEnd) print(startDateStr) print(endDateStr)