NSDate beginning of day and end of day

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


        
23条回答
  •  粉色の甜心
    2020-11-30 00:07

    Since iOS 8.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ there is a built in function in the Foundation, which you can use out of the box. No need to implement own functions.

    public func startOfDay(for date: Date) -> Date

    So you can use it this way:

    let midnightDate = Calendar(identifier: .gregorian).startOfDay(for: Date())

    It's worth to remember, that this takes upon consideration the device time zone. You can set .timeZone on calendar if you want to have eg UTC zone.

    Link to the Apple reference pages: https://developer.apple.com/reference/foundation/nscalendar/1417161-startofday.

提交回复
热议问题