iOS之Swift开发iOS开发iOS学习

如何使用 Swift 获取 NSDate() 的当前年、月、日?

2017-03-20  本文已影响280人  张嘉夫

只要这么做就不会再浪费更多美好的生命在处理这件事情上,如下所示...

Swift 1.x

        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear, fromDate: date)
        
        let year =  components.year
        let month = components.month
        let day = components.day

Swift 2.x

        let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components([.Day , .Month , .Year], fromDate: date)
        
        let year =  components.year
        let month = components.month
        let day = components.day
        
        print(year)
        print(month)
        print(day)

Swift 3.x

//作为 swift 3 的一个特色,苹果移除了 NS,让代码更简单了
//现在的代码会是:
 
let date = Date()
let calendar = Calendar.current
 
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)

可以使用这里提供的多个变量来组成多种日期组件:https://developer.apple.com/reference/foundation/nsdatecomponents

上一篇 下一篇

猜你喜欢

热点阅读