swift - 迄今为止的数字 - Swift

标签 swift nsdate nscalendar

获取一年中的第几天很简单,例如

func dayOfYear(inputDate:NSDate) -> (Int) {
    let cal         = NSCalendar.currentCalendar()
    let returnDay   = cal.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: inputDate)
    return returnDay
}

但是你如何做相反的事情呢?它显然只会返回日期/月份。我可以轻松编写繁琐的反算例程,但有没有聪明的方法?

最佳答案

是的,NSCalendar 提供了一种将日历组件合并到单个日期对象中的方法。看看我在 Playground 中写的这个例子:

import UIKit
import Foundation

let inputDate: NSDate = NSDate()
let calendar = NSCalendar.currentCalendar()
let day = calendar.ordinalityOfUnit(.CalendarUnitDay, inUnit: .CalendarUnitYear, forDate: inputDate)

let components = NSDateComponents()
components.day = day

let date = calendar.dateFromComponents(components)

根据文档,

When there are insufficient components provided to completely specify an absolute time, a calendar uses default values of its choice. When there is inconsistent information, a calendar may ignore some of the components parameters or the method may return nil. Unnecessary components are ignored (for example, Day takes precedence over Weekday and Weekday ordinals).

此外,

Note that some computations can take a relatively long time to perform.

参见 NSCalendar Class Reference获取更多信息。

关于swift - 迄今为止的数字 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31399513/

相关文章:

swift - 将 iOS 分段控件转换为 CFTimeInterval 类型

ios - 使用导致内存泄漏的音频剪辑

ios - 将字符串日期转换为 NSDate

objective-c - 我应该保留 NSCalendar 对象以供持久使用吗?

swift - 如何在 SceneKit 中实现角度检测滑动手势识别器?

ios - swift : addSubview before StoryBoard

iphone - 如何知道两个 NSDate 是否在同一天

ios - 将 UTC 日期格式转换为本地 nsdate

Objective-C:获取日历年中的天数

ios - 如何在swift 3中每天在特定时间触发本地通知