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

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

var date = NSDate()

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

var hour = date.hour

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


当前回答

仅用于特定格式的日期

    let dateFormatter1 = NSDateFormatter()
    dateFormatter1.dateStyle = .MediumStyle
    dateFormatter1.timeStyle = .NoStyle
    dateFormatter1.dateFormat = "dd-MM-yyyy"
    let date = dateFormatter1.stringFromDate(NSDate())

其他回答

仅用于特定格式的日期

    let dateFormatter1 = NSDateFormatter()
    dateFormatter1.dateStyle = .MediumStyle
    dateFormatter1.timeStyle = .NoStyle
    dateFormatter1.dateFormat = "dd-MM-yyyy"
    let date = dateFormatter1.stringFromDate(NSDate())

Xcode 8.2.1•Swift 3.0.2

extension Date {
    var hour: Int { return Calendar.autoupdatingCurrent.component(.hour, from: self) }
}

let date = Date()      // "Mar 16, 2017, 3:43 PM"
let hour = date.hour   // 15

你可以从Dateformatter获取

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

Swift 3更新:

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)

我是这样做的:

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute

在objective-c中看到同样的问题,我如何从NSDate中获得小时和分钟?

和Nate的答案相比,你得到的是数字,而不是字符串……

func getCurrentDate() -> Date {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let dateInString  = dateFormatter.string(from: date)
    let dateinDate = dateFormatter.date(from: dateInString)
    return dateinDate!
}