我有一个 NSDate
对象,我想将它设置为任意时间(例如,午夜),这样我就可以使用 timeIntervalSince1970
函数来一致地检索数据,而无需担心创建对象的时间。
我试过使用 NSCalendar
并使用一些 Objective-C 方法修改其组件,如下所示:
let date: NSDate = NSDate()
let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
let components: NSDateComponents = cal.components(NSCalendarUnit./* a unit of time */CalendarUnit, fromDate: date)
let newDate: NSDate = cal.dateFromComponents(components)
上述方法的问题是只能设置一个时间单位(/*一个时间单位*/
),所以只能有以下其中一项是准确的:
- 天
- 月份
- 年份
- 营业时间
- session 记录
- 秒
有没有办法同时设置时、分、秒并保留日期(日/月/年)?
最佳答案
你的声明
The problem with the above method is that you can only set one unit of time ...
不正确。 NSCalendarUnit
符合 RawOptionSetType
协议(protocol)
继承自 BitwiseOperationsType
。这意味着选项可以按位
结合 &
和 |
。
在 Swift 2 (Xcode 7) 中再次更改为
OptionSetType
提供类似集合的接口(interface),请参阅
例如 Error combining NSCalendarUnit with OR (pipe) in Swift 2.0 .
因此以下代码在 iOS 7 和 iOS 8 中编译和工作:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
// Swift 1.2:
let components = cal.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
// Swift 2:
let components = cal.components([.Day , .Month, .Year ], fromDate: date)
let newDate = cal.dateFromComponents(components)
(请注意,我省略了变量的类型注释,Swift 编译器 从右侧的表达式自动推断类型 作业。)
确定给定一天(午夜)的开始也可以完成
使用 rangeOfUnit()
方法(iOS 7 和 iOS 8):
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var newDate : NSDate?
// Swift 1.2:
cal.rangeOfUnit(.CalendarUnitDay, startDate: &newDate, interval: nil, forDate: date)
// Swift 2:
cal.rangeOfUnit(.Day, startDate: &newDate, interval: nil, forDate: date)
如果您的部署目标是 iOS 8 那么它就更简单了:
let date = NSDate()
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let newDate = cal.startOfDayForDate(date)
Swift 3 (Xcode 8) 更新:
let date = Date()
let cal = Calendar(identifier: .gregorian)
let newDate = cal.startOfDay(for: date)
关于ios - 如何将 NSDate 对象设置为午夜?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26189656/