NSDate beginning of day and end of day

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


        
23条回答
  •  南方客
    南方客 (楼主)
    2020-11-30 00:15

    Swift3 Using *XCode8
    Apple is removing the NS from the class name so that NSDate can be swapped out to Date. You may get a compiler warning if you try to cast them saying they will always fail, but they work fine when you run them in the playground.

    I replaced my generated NSDate in core data model with Date and they still work.

    extension Date {
      func startTime() -> Date {
        return Calendar.current.startOfDay(for: self)
      }
    
      func endTime() -> Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startTime())!
      }
    }
    

提交回复
热议问题