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

how to get start and end time of today's date in ios?

我正在使用此代码获取当前日期和时间

    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

如何获取当前日期的开始和结束时间?

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

//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)

编辑: 将日期转换为字符串

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)