0

I am using Swift 3 and trying to get the current hour. Below is the code i have written to get the current hour but it gives an error.

let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date) // error

What could be the reason for this, all the sample code based on Swift 3 shows the same code snippet to get the current hour but it just don't seem to work. Please can anyone point out what could be wrong here. Thanks.

Parag Kadam
  • 3,620
  • 5
  • 25
  • 51
  • 4
    Compiles fine for me – I would hazard a guess that you've defined your own `Date` type which is shadowing Foundation's `Date`. – Hamish Mar 10 '17 at 12:00
  • Cannot reproduce. Compiles and runs as expected. – Martin R Mar 10 '17 at 12:00
  • 1
    its works perfectly – Anbu.Karthik Mar 10 '17 at 12:00
  • @Hamish : this is the only code I have written , It somehow seems to be a bug in my Xcode as it is showing me random errors and to get rid of it i often have to rebuild and clean the project. – Parag Kadam Mar 10 '17 at 12:03
  • Are you using Xcode 8 and Swift 3? Try creating a new playground containing only this code. – Duncan C Mar 10 '17 at 12:11
  • Yes I am using xcode 8 with swift 3. OK will try creating a new project. – Parag Kadam Mar 10 '17 at 12:15
  • Please check [How to get time (hour, minute, second) in Swift 3 using NSDate?](http://stackoverflow.com/questions/38248941/how-to-get-time-hour-minute-second-in-swift-3-using-nsdate) – Shahrukh Mar 10 '17 at 13:54
  • Hamish: you were so right I indeed had made a class named Date which was shadowing Foundation's Date class. Coming from java background I pretty much used to seeing all my imports at the top of the file itself unlike swift which induced the error . Thanks. – Parag Kadam Mar 10 '17 at 18:43

2 Answers2

-2

Try this code to get hour in swift 3 :

let calendar = NSCalendar.current
let hour = calendar.component(.hour, from:  NSDate() as Date)
Vikash Kumar
  • 642
  • 1
  • 11
  • 25
-3

Use this code to get a current hour:

let date = Date()
let formatter = NSDateFormatter()
formatter.setFormat = "h"
print(formatter.stringFromDate(date))

Note: I did not run this code in xcode so don't just copy paste.

NotABot
  • 516
  • 1
  • 8
  • 27