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

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

var date = NSDate()

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

var hour = date.hour

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


当前回答

我知道有很多答案,但我认为我的答案对许多人来说可能更方便

extension String {
    init(epoch: Double) {
        let date = Date(timeIntervalSince1970: epoch)

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ssZZZ"

        self = dateFormatter.string(from: date)
    }
}

其他回答

斯威夫特4

let dateFormatter : DateFormatter = DateFormatter()
//  dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.dateFormat = "yyyy-MMM-dd HH:mm:ss"
let date = Date()
let dateString = dateFormatter.string(from: date)
let interval = date.timeIntervalSince1970

输出

2018 - 5月- 01 10:41:31

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!
}

斯威夫特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
        }
}

迅速回答:

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

使用Swift 5 (Xcode 10 & Xcode 11)(来自法国UTC)

func getCurrentDateTime() {
    let now = Date()
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "fr_FR")
    formatter.dateFormat = "EEEE dd MMMM YYYY HH:mm"
    myLabel.text = formatter.string(from: now)
    myLabel.font = UIFont(name: "HelveticaNeue-Light", size: 12)
    myLabel.textColor = UIColor.black
}

如果您只想显示日期,请设置formatter.dateFormat

formatter.dateFormat = "EEEE dd MMMM YYYY"

若要只显示小时,请更改格式化程序。dateFormat来

formatter.dateFormat = "HH:mm"

不要忘记在viewDidLoad上添加getCurrentDateTime()。