120
-(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];

}

当我打电话时:[self endOfDay:[NSDate date]]; 我得到了本月的第一天......为什么会这样?我使用这两种方法是因为我需要一个从第一个日期的第一秒 (beginningOfDay:date1) 到第二个日期的最后一秒 (endOfDay:Date2) 的间隔...

4

25 回答 25

255

一天的开始/一天的结束——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
于 2013-11-23T05:29:21.817 回答
38

Swift 5 简单而准确的答案。

开始时间:00:00:00

结束时间:23:59:59.5

let date = Date() // current date or replace with a specific date
let calendar = Calendar.current
let startTime = calendar.startOfDay(for: date)
let endTime = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: date)

额外的

let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: noon)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: noon)!
let specificDate = Date("2020-01-01")

extension Date {
    init(_ dateString:String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        dateStringFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale
        let date = dateStringFormatter.date(from: dateString)!
        self.init(timeInterval:0, since:date)
    }
}
于 2018-02-08T22:39:53.187 回答
35

你错过NSDayCalendarUnit

NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];
于 2012-11-10T18:15:26.243 回答
28

在 iOS 8+ 中,这真的很方便;你可以做:

let startOfDay: Date = Calendar.current.startOfDay(for: Date())

要获得一天的结束,只需使用日历方法 23 小时 59 分钟 59 秒,具体取决于您如何定义一天结束。

// Swift 5.0
let components = DateComponents(hour: 23, minute: 59, second: 59)
let endOfDay = Calendar.current.date(byAdding: components, to: startOfDay)

日期数学

Apple iOS NSCalendar 文档。(见章节:历法计算

NSHipster 讨论的 NSCalendar 方法

于 2015-08-18T04:41:47.183 回答
17

我对 NSDate 的 Swift 扩展:

斯威夫特 1.2

extension NSDate {

    func beginningOfDay() -> NSDate {
        var calendar = NSCalendar.currentCalendar()
        var components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: self)
        return calendar.dateFromComponents(components)!
    }

    func endOfDay() -> NSDate {
        var components = NSDateComponents()
        components.day = 1
        var date = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: self.beginningOfDay(), options: .allZeros)!
        date = date.dateByAddingTimeInterval(-1)!
        return date
    }
}

斯威夫特 2.0

extension NSDate {

    func beginningOfDay() -> NSDate {
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Year, .Month, .Day], fromDate: self)
        return calendar.dateFromComponents(components)!
    }

    func endOfDay() -> NSDate {
        let components = NSDateComponents()
        components.day = 1
        var date = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: self.beginningOfDay(), options: [])!
        date = date.dateByAddingTimeInterval(-1)
        return date
    }
}
于 2015-04-01T07:02:15.697 回答
15

Swift 5.1 - XCode 11Date类代替NSDateCalender代替NSCalender

extension Date {

    var startOfDay : Date {
        let calendar = Calendar.current
        let unitFlags = Set<Calendar.Component>([.year, .month, .day])
        let components = calendar.dateComponents(unitFlags, from: self)
        return calendar.date(from: components)!
   }

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

用法:

    let myDate = Date()
    let startOfDate = myDate.startOfDay
    let endOfDate = myDate.endOfDay
于 2016-10-22T13:36:10.213 回答
9

我认为在 Swift 中最简洁的方法如下:

extension Date {
    func startOfDay() -> Date {
        return Calendar.current.startOfDay(for: self)
    }
    func endOfDay() -> Date {
        return Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, of: self) ?? self
    }
}
于 2020-04-26T14:28:39.923 回答
6

在 Swift 3 及更高版本中

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

用法:

var currentDayStart = Date().startOfDayDate
var currentDayEnd = Date().endOfDayDate
于 2019-07-24T08:24:09.387 回答
4

您不必将组件设置为零,只需忽略它们:

-(NSDate *)beginningOfDay:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
    return [calendar dateFromComponents:components];
}
于 2014-01-02T13:01:18.113 回答
4

对我来说,这里和stackoverflow上的其他地方都没有答案。为了开始今天,我这样做了。

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];

注意这一点[gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

创建日历时,它会使用当前时区进行初始化,并且当从其组件中提取日期时,由于 NSDate 没有时区,因此当前时区的日期被视为 UTC 时区。所以我们需要在提取组件之前设置时区,然后在从这些组件中提取日期时设置时区。

于 2015-07-07T19:57:39.610 回答
4

斯威夫特 3

  class func today() -> NSDate {
        return NSDate()
    }

    class func dayStart() -> NSDate {
          return NSCalendar.current.startOfDay(for: NSDate() as Date) as NSDate
    }

    class func dayEnd() -> NSDate {
        let components = NSDateComponents()
        components.day = 1
        components.second = -1
        return NSCalendar.current.date(byAdding: components as DateComponents, to: self.dayStart() as Date)
    }
于 2016-10-10T06:03:49.693 回答
4

Swift3 Using *XCode8
Apple 正在NS从类名中删除 ,以便NSDate可以将其换成Date. 如果您尝试强制转换它们说它们总是会失败,您可能会收到编译器警告,但是当您在操场上运行它们时它们可以正常工作。

我用生成NSDate的核心数据模型替换了Date它们,它们仍然有效。

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())!
  }
}
于 2016-10-23T08:51:09.403 回答
3

Objective-C

NSCalendar * calendar = [NSCalendar currentCalendar];
NSDate * startDate = [calendar startOfDayForDate:[NSDate date]];
NSLog(@"start date is %@", startDate);
于 2018-02-27T08:55:27.333 回答
2

您缺少NSDayCalendarUnit组件。

于 2012-11-10T18:17:50.293 回答
2

获得结果的另一种方法:

NSDate *date = [NSDate date];

NSDateComponents *components = [[NSDateComponents alloc] init];
components.day = [[NSCalendar currentCalendar] ordinalityOfUnit:(NSCalendarUnitDay) inUnit:(NSCalendarUnitEra) forDate:date];
NSDate *dayBegin = [[NSCalendar currentCalendar] dateFromComponents:components];

components.day += 1;
NSDate *dayEnd = [[NSCalendar currentCalendar] dateFromComponents:components];
于 2015-05-29T22:03:50.203 回答
2

在 Swift 5.3 中,Calendar.current.startOfDay() 和 Calendar.current.date(bySettingHour:, minute:, second:, of:) 都是时区特定的。如果您希望无论时区如何,您的日期都标准化为同一时间,您应该像这样使用 GMT 时间。

// Normalize time of aDate to 12:00 GMT
let aDate = Date()
let twelveGMT = 12 + TimeZone.current.secondsFromGMT() / 3600
let normalizedDate = Calendar.current.date(bySettingHour: twelveGMT, minute: 0, second: 0, of: aDate)
于 2020-11-29T05:11:30.520 回答
2

对于迅捷4

    var calendar = Calendar.current
    calendar.timeZone = NSTimeZone(abbreviation: "UTC")! as TimeZone
    let dateAtMidnight = calendar.startOfDay(for: Date())

    //For End Date
    var components = DateComponents()
    components.day = 1
    components.second = -1

    let dateAtEnd = calendar.date(byAdding: components, to: dateAtMidnight)

    print("dateAtMidnight :: \(dateAtMidnight)")
    print("dateAtEnd :: \(dateAtEnd!)")
于 2018-10-09T16:00:57.907 回答
1

更新@Zelko 的答案以获取日历:

extension Date {

    func startOfDay(in calendar: Calendar = .current) -> Date {
        calendar.startOfDay(for: self)
    }

    func endOfDay(in calendar: Calendar = .current) -> Date {
        var components = DateComponents()
        components.day = 1
        components.second = -1
        return calendar.date(byAdding: components, to: startOfDay(in: calendar))!
    }

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

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

笔记:

当您的应用支持更多地区时,使用正确的日历非常重要

于 2022-01-26T10:36:22.500 回答
1

由于iOS 8.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+Foundation 中有一个内置功能,您可以开箱即用。无需实现自己的功能。

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

所以你可以这样使用它:

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

值得记住的是,这需要考虑设备时区。如果您想拥有例如 UTC 区域,您可以设置.timeZone为 on 。calendar

链接到 Apple 参考页面:https ://developer.apple.com/reference/foundation/nscalendar/1417161-startofday 。

于 2016-12-01T07:40:21.280 回答
1

这是我用于 Swift 4.2 的:

    let calendar = Calendar.current
    let fromDate = calendar.startOfDay(for: Date())
    let endDate = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: Date())

对我来说就像一个魅力。您可以将它添加到开始日期和结束日期的扩展名中Date,但请记住,添加扩展名会增加编译时间(除非在与类相同的文件中),因此如果您只需要在一个地方或一个类中使用它。 ..不要使用扩展名。

于 2019-03-05T08:11:35.480 回答
1

dateInterval(of:start:interval:for:)使用ofCalendar和专用DateInterval结构的另一种方式

返回时startDate包含一天的开始时间和一天interval中的秒数。

func dateInterval(of date : Date) -> DateInterval {
    var startDate = Date()
    var interval : TimeInterval = 0.0
    Calendar.current.dateInterval(of: .day, start: &startDate, interval: &interval, for: date)
    return DateInterval(start: startDate, duration: interval-1)
}

let interval = dateInterval(of: Date())
print(interval.start, interval.end)
于 2016-09-12T13:07:11.647 回答
0

仅供参考,在 Swift 4 中设置一天的开始和结束的简单方法

var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
comp.hour = 0
comp.minute = 0
comp.second = 0
comp.timeZone = TimeZone(abbreviation: "UTC")!


//Set Start of Day
let startDate : Date = Calendar.current.date(from: comp)!
print(“Day of Start : \(startDate)")


//Set End of Day
comp.hour = 23
comp.minute = 59
comp.second = 59

let endDate : Date = Calendar.current.date(from:comp)!
print("Day of End : \(endDate)")
于 2018-12-18T05:11:38.130 回答
0

由于Calendar结构包含startOfDay(for:),我发现最好将endOfDay(for:)方法封装在扩展中Calendar而不是 中Date

以下代码可以放在 Playground 文件中以便快速执行。

import Foundation

extension Calendar {

    func endOfDay(for date: Date) -> Date {

        // Get the start of the date argument.
        let dayStart = self.startOfDay(for: date)

        // Add one day to the start of the day 
        // in order to get the start of the following day.            
        guard let nextDayStart = self.date(byAdding: .day, value: 1, to: dayStart) else {
            preconditionFailure("Expected start of next day")
        }

        // Create date components that will subtract a single
        // second from the start of the next day. This will
        // allow you to get the last hour, last minute, and last
        // second of the previous day, which is the day for the 
        // date argument that was passed to this method.
        var components = DateComponents()
        components.second = -1

        // Add the date components to the date for the next 
        // day, which will perform the subtraction of the single
        // second. This will return the end of the day for the date
        // that was passed into this method.
        guard let dayEnd = self.date(byAdding: components, to: nextDayStart) else {
            preconditionFailure("Expected end of day")
        }

        // Simply return the date value.
        return dayEnd
    }

}

要查看格式化的日期,请创建一个DateFormatter并打印输出。

let formatter = DateFormatter()
formatter.dateStyle = .long
formatter.timeStyle = .long
Calendar.current.endOfDay(for: Date()) // "Dec 31, 2020 at 11:59 PM"
于 2020-12-31T15:12:38.937 回答
0
extension Date {
    func stringFrom(dateFormat: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = dateFormat
        return formatter.string(from: self)
    }

    func firstSecondInDay() -> Date {
        let dayStr = self.stringFrom(dateFormat: "yyyy-MM-dd")
        let firstSecondStr = "\(dayStr) 00:00:00"
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return format.date(from: firstSecondStr)!
    }

    func lastSecondInDay() -> Date {
        let dayStr = self.stringFrom(dateFormat: "yyyy-MM-dd")
        let laseSecondStr = "\(dayStr) 23:59:59"
        let format = DateFormatter()
        format.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return format.date(from: laseSecondStr)!
    }
}
于 2017-11-03T07:52:03.643 回答
-1

日历单位应被视为间隔。从 iOS 10Calendar开始,对此有一些不错的方法

let day = Calendar.autoupdatingCurrent.dateInterval(of: .day, for: Date())
day?.start
day?.end.addingTimeInterval(-1)

您可以使用相同的方法来获取任何日历组件(周/月/年等)的开始/结束

这里需要注意的是,没有一个时间点可以定义为结束(假设我们有一个开始)。以上将在一天结束前一秒钟(23:59:59)。

于 2019-04-21T16:21:00.220 回答