gpt4 book ai didi

swift - 迄今为止的数字 - Swift

转载 作者:搜寻专家 更新时间:2023-11-01 07:33:01 25 4
gpt4 key购买 nike

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

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/

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