【问题标题】:NSCalendar ordinalityOfUnit doesn't return the day of the week correctlyNSCalendar ordinalityOfUnit 不能正确返回星期几
【发布时间】:2017-12-18 09:32:37
【问题描述】:

我必须在 Objective C 课程中确定星期几。 尝试使用此方法:

- (NSUInteger)ordinalityOfUnit:(NSCalendarUnit)smaller 
                        inUnit:(NSCalendarUnit)larger 
                       forDate:(NSDate *)date; 

这是我的代码:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
(int) [gregorian ordinalityOfUnit:NSCalendarUnitWeekday inUnit:NSCalendarUnitWeekday forDate:[NSDate date]];

无论是哪一天,它总是返回 -1。即使我更改日期,或者循环一整周。 但是,使用这种方法,效果很好:

- (NSDateComponents *)components:(NSCalendarUnit)unitFlags 
                        fromDate:(NSDate *)date;

到目前为止一切顺利。唯一的问题是:此方法已弃用(在 iOS 8.0 中首次弃用,所以很久以前)。 有点害怕使用过时的旧方法进行生产。有没有办法使(甚至不是非常)新方法起作用?

【问题讨论】:

  • developer.apple.com/documentation/foundation/nscalendar/… 我没有看到它被弃用。 iOS8 中可能被弃用的是NSWeekdayCalendarUnit vs NSCalendarUnitWeekday
  • 另外,查看ordinalityOfUnit:inUnit:forDate: 的文档。它说在某些情况下返回NSNotFound(比如smaller >= larger? 因为在你的情况下它们是相等的),NSNotFound 可以转换为-1 从铸造NSUInteger 到@987654334 @
  • Larme:你是对的。谢谢!这是一个简单的修复......

标签: ios objective-c nscalendar


【解决方案1】:

来自ordinalityOfUnit:inUnit:forDate: 文档:

对于给定的绝对时间,返回指定较大日历单位(例如一周)内较小日历单位(例如一天)的序数。

你已经为前两个参数指定了相同的单位,你需要为第一个指定天,第二个指定周:

[gregorian ordinalityOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitWeekOfMonth forDate:[NSDate date]]

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2011-06-06
    • 1970-01-01
    相关资源
    最近更新 更多