NSDate beginning of day and end of day

后端 未结 23 2093
广开言路
广开言路 2020-11-29 23:28
    -(NSDate *)beginningOfDay:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSMonthCalend         


        
23条回答
  •  孤城傲影
    2020-11-30 00:12

    In Swift 3 and above

    extension Date {
        var startOfDayDate: Date {
            return Calendar.current.startOfDay(for: self)
        }
    
        var endOfDayDate: Date {
            let nextDayDate = Calendar.current.date(byAdding: .day, value: 1, to: self.startOfDayDate)!
            return nextDayDate.addingTimeInterval(-1)
        }
    }
    

    Usage:

    var currentDayStart = Date().startOfDayDate
    var currentDayEnd = Date().endOfDayDate
    

提交回复
热议问题