ios – NSDate一年中的日子(swift)

一年中的日数如何发现?有没有一个简单的方法,我没有看到,或者我必须找到从1月1日到当前日期的秒数除以一天中的秒数?

解决方法

这是将 How do you calculate the day of the year for a specific date in Objective-C?的答案翻译成Swift.

Swift 2:

let date = NSDate() // now
let cal = NSCalendar.currentCalendar()
let day = cal.ordinalityOfUnit(.Day,inUnit: .Year,forDate: date)
print(day)

Swift 3:

let date = Date() // now
let cal = Calendar.current
let day = cal.ordinality(of: .day,in: .year,for: date)
print(day)

今年第一天为1,今天(二月二十五日)为56 = 31 25.

… or do I have to find the number of seconds from Jan 1 to the current date
and divide by the number of seconds in a day

这是一个错误的做法,因为一天没有固定的秒数(从夏令时转换到夏令时间).

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...