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

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

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...