Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current time in Swift?

Tags:

date

swift

nsdate

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?

like image 266
Recusiwe Avatar asked Dec 15 '22 05:12

Recusiwe


2 Answers

Change

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

to

let components = calender.components([.Hour, .Minute], fromDate: date)
like image 132
Casey Fleser Avatar answered Jan 14 '23 20:01

Casey Fleser


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.

like image 37
rob mayoff Avatar answered Jan 14 '23 19:01

rob mayoff