ios 如何检查两个 NSDates 是否来自同一天
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37426662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if two NSDates are from the same day
提问by JoshJoshJosh
I am working on ios development and I find it really hard to check if two NSDates are from the same day. I tried to use this
我正在从事 ios 开发,我发现很难检查两个 NSDate 是否来自同一天。我试着用这个
fetchDateList()
// Check date
let date = NSDate()
// setup date formatter
let dateFormatter = NSDateFormatter()
// set current time zone
dateFormatter.locale = NSLocale.currentLocale()
let latestDate = dataList[dataList.count-1].valueForKey("representDate") as! NSDate
//let newDate = dateFormatter.stringFromDate(date)
let diffDateComponent = NSCalendar.currentCalendar().components([NSCalendarUnit.Year, NSCalendarUnit.Month, NSCalendarUnit.Day], fromDate: latestDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))
print(diffDateComponent.day)
but it just checks if two NSDates has a difference of 24 hours. I think there is a way to make it work but still, I wish to have NSDate values before 2 am in the morning to be count as the day before, so I definitely need some help here. Thanks!
但它只是检查两个 NSDates 是否有 24 小时的差异。我认为有一种方法可以使它工作,但我仍然希望在凌晨 2 点之前将 NSDate 值计算为前一天,所以我在这里肯定需要一些帮助。谢谢!
回答by Catfish_Man
NSCalendar has a method that does exactly what you want actually!
NSCalendar 有一个方法,可以做你真正想要的!
/*
This API compares the Days of the given dates, reporting them equal if they are in the same Day.
*/
- (BOOL)isDate:(NSDate *)date1 inSameDayAsDate:(NSDate *)date2 NS_AVAILABLE(10_9, 8_0);
So you'd use it like this:
所以你会像这样使用它:
[[NSCalendar currentCalendar] isDate:date1 inSameDayAsDate:date2];
Or in Swift
或者在斯威夫特
Calendar.current.isDate(date1, inSameDayAs:date2)
回答by Mike Henderson
You should compare the date components:
您应该比较日期组件:
let date1 = NSDate(timeIntervalSinceNow: 0)
let date2 = NSDate(timeIntervalSinceNow: 3600)
let components1 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date1)
let components2 = NSCalendar.currentCalendar().components([.Year, .Month, .Day], fromDate: date2)
if components1.year == components2.year && components1.month == components2.month && components1.day == components2.day {
print("same date")
} else {
print("different date")
}
Or shorter:
或更短:
let diff = Calendar.current.dateComponents([.day], from: self, to: date)
if diff.day == 0 {
print("same day")
} else {
print("different day")
}