NSDate一年中的一天(swift) [英] NSDate day of the year (swift)

查看:166
本文介绍了NSDate一年中的一天(swift)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How might the day number of the year be found with swift? Is there a simple way that I'm not seeing, 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?

推荐答案

这是如何计算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 ,今天(2月) 56 = 31 + 25 25)。

This gives 1 for the first day in the year, and 56 = 31 + 25 for today (Feb 25).


...或者我必须找到1月的秒数1到当前日期
并除以一天中的秒数

... 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

这是一种错误的方法,因为一天没有固定的
秒数(从夏令时转换到夏令时)。

This would be a wrong approach, because a day does not have a fixed number of seconds (transition from or to Daylight Saving Time).

这篇关于NSDate一年中的一天(swift)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆