gpt4 book ai didi

iphone - 比较 NSDate 的某些组件?

转载 作者:行者123 更新时间:2023-12-03 18:50:55 25 4
gpt4 key购买 nike

如何仅比较 2 个 NSDate 的年月日组件?

最佳答案

因此,您可以这样做:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger desiredComponents = (NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit);

NSDate *firstDate = ...; // one date
NSDate *secondDate = ...; // the other date

NSDateComponents *firstComponents = [calendar components:desiredComponents fromDate:firstDate];
NSDateComponents *secondComponents = [calendar components:desiredComponents fromDate:secondDate];

NSDate *truncatedFirst = [calendar dateFromComponents:firstComponents];
NSDate *truncatedSecond = [calendar dateFromComponents:secondComponents];

NSComparisonResult result = [truncatedFirst compare:truncatedSecond];
if (result == NSOrderedAscending) {
//firstDate is before secondDate
} else if (result == NSOrderedDescending) {
//firstDate is after secondDate
} else {
//firstDate is the same day/month/year as secondDate
}

基本上,我们获取两个日期,去掉它们的小时-分钟-秒位,然后将它们转回日期。然后我们比较这些日期(不再有时间部分;只有日期部分)并查看它们之间的比较情况。

警告:在浏览器中输入但未编译。警告实现者

关于iphone - 比较 NSDate 的某些组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com