OStack程序员社区-中国程序员成长平台

标题: ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 22:18
标题: ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果

NSDateComponents 解决了我的问题,但我想了解为什么这种方法如此有效

NSDate *today = [NSDate date];
NSLog(@"today is: %@", today);

NSDate *dayChanged = [calendar dateBySettingUnitNSCalendarUnitDay)
                                           value:10
                                          ofDate:today
                                         options:0];
NSLog(@"dayChanged is: %@", dayChanged);

NSDate *monthChanged = [calendar dateBySettingUnitNSCalendarUnitMonth)
                                             value:5
                                            ofDate:today
                                           options:0];
NSLog(@"monthChanged is: %@", monthChanged);

结果是:

today is: 2016-09-30 06:40:36 +0000
dayChanged is: 2016-10-10 00:00:00 +0000
monthChanged is: 2017-05-01 00:00:00 +0000

为什么 dateBySettingUnit 增加下一个更大的单位?



Best Answer-推荐答案


根据观察,dateBySettingUnit does not return past date

因此,对于使用 dateBySettingUnit 对 future 日期的快速测试设置可以按预期工作,请参见以下代码:

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *today = [NSDate date];
NSLog(@"today is: %@", today);

NSDate *dayChanged = [calendar dateBySettingUnitNSCalendarUnitDay)
                                           value:31
                                          ofDate:today
                                         options:NSCalendarWrapComponents];
NSLog(@"dayChanged is: %@", dayChanged);

NSDate *monthChanged = [calendar dateBySettingUnitNSCalendarUnitMonth)
                                             value:12
                                            ofDate:dayChanged
                                           options:NSCalendarWrapComponents];
NSLog(@"monthChanged is: %@", monthChanged);

日志:

2016-09-30 12:58:30.506 TestRegex[3785:72957] today is: 2016-09-30 07:58:30 +0000
2016-09-30 12:58:30.508 TestRegex[3785:72957] dayChanged is: 2016-09-30 19:00:00 +0000
2016-09-30 12:58:30.509 TestRegex[3785:72957] monthChanged is: 2016-11-30 19:00:00 +0000

您可以尝试实际计算偏移量的链接答案中提到的 NSCalendar 扩展,或者您可以使用 NSDateComponents 解决方案:

 NSDateComponents *comps = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:today];
[comps setCalendar:calendar];
[comps setDay:5];

希望有帮助!

关于ios - NSCalendar 的 dateBySettingUnit 方法返回不明显的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39785430/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4