ios - Swift 4: 获取Date对象日期的当日起点和终点时间

light-ios

2018-03-28T13:35:32Z||2018-03-28T13:35:32Z

使用Swift 4和Date.

import Foundation

extension Date {
    var startOfDay: Date {
        return Calendar.current.startOfDay(for: self)
    }
    
    var endOfDay: Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startOfDay) ?? self
    }
}

实验:

let now = Date()
now.startOfDay
now.endOfDay

输出:

"28 Mar 2018 at 9:33 PM"
"28 Mar 2018 at 12:00 AM"
"28 Mar 2018 at 11:59 PM"