NSDate beginning of day and end of day

2019-01-07 07:56发布

    -(NSDate *)beginningOfDay:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];

    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];

    return [cal dateFromComponents:components];

}

-(NSDate *)endOfDay:(NSDate *)date
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(  NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];

    [components setHour:23];
    [components setMinute:59];
    [components setSecond:59];

    return [cal dateFromComponents:components];

}

When I call : [self endOfDay:[NSDate date]]; I get the first of the month ... Why is that? I use this two methods because I need an interval that is from the first second of the first date (beginningOfDay:date1) to the last second of the second date (endOfDay:Date2) ...

18条回答
2楼-- · 2019-01-07 08:39

For me none of the answers here and else where on stackoverflow worked. To get start of today i did this.

NSCalendar * gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; 
[gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    
NSDateComponents *components = [gregorian components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]]; 
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; 
NSDate *beginningOfToday = [gregorian dateFromComponents:components];

Note this [gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; and [components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];.

When a calendar is created it gets initialised with current timezone and when date is extracted from its components, since NSDate has no timezone, the date from current timezone is considered as UTC timezone. So we need to set the timezone before extracting components and later when extracting date from these components.

查看更多
Anthone
3楼-- · 2019-01-07 08:40

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())!
  }
}
查看更多
该账号已被封号
4楼-- · 2019-01-07 08:40

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.

查看更多
甜甜的少女心
5楼-- · 2019-01-07 08:41

You are missing NSDayCalendarUnit in

NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];
查看更多
Deceive 欺骗
6楼-- · 2019-01-07 08:42

Swift 4 Simple and more precise answer.

Start time: 00:00:00

End time: 23:59:59.5

var date = Date() // current date or replace with a specific date
var calendar = Calendar.current
let startTime = calendar.startOfDay(for: date)
let endTime = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: date)
查看更多
倾城 Initia
7楼-- · 2019-01-07 08:43

Start Of Day / End Of Day — Swift 4

  // Extension

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)!
    }

    var startOfMonth: Date {
        let components = Calendar.current.dateComponents([.year, .month], from: startOfDay)
        return Calendar.current.date(from: components)!
    }

    var endOfMonth: Date {
        var components = DateComponents()
        components.month = 1
        components.second = -1
        return Calendar.current.date(byAdding: components, to: startOfMonth)!
    }
}

// End of day = Start of tomorrow minus 1 second
// End of month = Start of next month minus 1 second
查看更多
登录 后发表回答