Recusiwe
Recusiwe

Reputation: 1138

How to get current time in Swift?

I'm trying to get the current time, and I've done this so far:

    let date = NSDate()
    let calender = NSCalendar.currentCalendar()
    let components = calender.component([.Hour, .Minute], fromDate: date)

And I then try to get the hour of the components

    let hour = components.hour

This give me "Value of type "Int" has no member 'hour'". Any suggestions?

Upvotes: 4

Views: 14157

Answers (3)

Deepak Tagadiya
Deepak Tagadiya

Reputation: 2237

swift 4

let hh2 = (Calendar.current.component(.hour, from: Date()))
let mm2 = (Calendar.current.component(.minute, from: Date()))
let ss2 = (Calendar.current.component(.second, from: Date()))

print(hh2,":", mm2,":", ss2) 

 output: ---> 9 : 10 : 55

Upvotes: 1

rob mayoff
rob mayoff

Reputation: 385500

NSCalendar.component(_:fromDate:) returns a single component of a date, as an Int. So your components variable is actually of type Int. Passing multiple units to component(_:fromDate:) (as you are doing) is undefined.

Try this instead:

let components = calender.components([.Hour, .Minute], fromDate: date)

Note that the first part of the method name here is components, not component.

Also, you might want to change your calender variable to calendar, since that is the correct spelling.

Upvotes: 4

Casey Fleser
Casey Fleser

Reputation: 5787

Change

let components = calender.component([.Hour, .Minute], fromDate: date)

to

let components = calender.components([.Hour, .Minute], fromDate: date)

Upvotes: 7

Related Questions