- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
获取一年中的第几天很简单,例如
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/
我在将一列转换为日期时遇到一些问题。 我希望将'01/02/98'(日、月、年)转换为'1998-02-01'(年、月、日). 以及如何将 '98' 转换为 1998。 最佳答案 I want thi
我正在从旧系统转换许多晦涩的日期格式。日期作为字符串解包/处理并转换为 ISO 8601 格式。 这个特定的函数尝试将 YYMMDD0F 转换为 YYYYMMDD ——函数名称说明了一切。从 2000
我是一名优秀的程序员,十分优秀!