我想检查当前NSDate
是否比另一个NSDate
提前2周。我可以在下面的代码中做一些事情但是想知道是否有任何正确的方法。
[calendar rangeOfUnit:NSCalendarUnitDay startDate:¤tDate interval:NULL forDate:currentDate];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&previousDate interval:NULL forDate:previousDate];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay fromDate:previousDate toDate:currentDate options:0];
if(diiference >= 14) {
}
答案 0 :(得分:0)
你可以在这里使用一个技巧。首先计算两个日期之间的天数,然后计算它们之间的周数。你可以像
那样做-(NSInteger)weeksBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime {
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
return [difference day] / 7;
}
如果你想获得像1.5这样的周值,你可以使用CGFloat
,如果你想要像1,2,3这样的周计数,你可以保持原样
答案 1 :(得分:0)
试试这个
目标C
+ (NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime
{
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&fromDate
interval:NULL forDate:fromDateTime];
[calendar rangeOfUnit:NSCalendarUnitDay startDate:&toDate
interval:NULL forDate:toDateTime];
NSDateComponents *difference = [calendar components:NSCalendarUnitDay
fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
<强>夫特强>
extension NSDate {
func numberOfDaysUntilDateTime(toDateTime: NSDate, inTimeZone timeZone: NSTimeZone? = nil) -> Int {
let calendar = NSCalendar.currentCalendar()
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
var fromDate: NSDate?, toDate: NSDate?
calendar.rangeOfUnit(.Day, startDate: &fromDate, interval: nil, forDate: self)
calendar.rangeOfUnit(.Day, startDate: &toDate, interval: nil, forDate: toDateTime)
let difference = calendar.components(.Day, fromDate: fromDate!, toDate: toDate!, options: [])
return difference.day
}
}