从操场开始。我正在尝试创建一个简单的应用程序。

我创建了一个date对象,就像这样:

var date = NSDate()

我怎样才能得到当前的时间?在其他语言中,我可以这样做:

var hour = date.hour

但我找不到任何这样的属性/方法。我找到了一个方法,dateWithCalendarFormat。我应该用这个吗?如果是,怎么做?


当前回答

斯威夫特5

func printTimestamp() {
    let timestamp = DateFormatter.localizedString(from: NSDate() as Date, dateStyle: .medium, timeStyle: .short)
    print(timestamp)
}

和调用函数printTimestamp()

其他回答

在Swift 3中,

    let date = Date()
    let calendar = Calendar.current()

    let hour = calendar.component(.hour, from: date)

迅速回答:

 let date = NSDate()
 let calendar = NSCalendar.currentCalendar()
 let components = calendar.components([.Hour, .Minute], fromDate: date)
 let hour = components.hour
 let minutes = components.minute

你可以从Dateformatter获取

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:Date())
print(dateString)

如果你只需要一天中的一小时

let calendar = NSCalendar.currentCalendar()
var hour = calendar.component(.Hour,fromDate: NSDate())

斯威夫特4:

extension Date
{
    func hour() -> Int
    {
    //Get Hour
    let calendar = Calendar.current
    let components = calendar.component(.hour, from: self)
    let hour = components

    //Return Hour
    return hour
    }


    func minute() -> Int
    {
    //Get Minute
    let calendar = Calendar.current
    let components = calendar.component(.minute, from: self)
    let minute = components

    //Return Minute
    return minute
        }
}