Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the hour of the day with Swift?

Tags:

ios

swift

nsdate

How would I get the hour of the day in Swift. I have tried NSCalendar and NSDateComponents, but I'm afraid I'm just starting with Swift.

like image 785
Samuel Gómez Avatar asked Jun 10 '14 09:06

Samuel Gómez


People also ask

How do I get only time in Swift?

To get only current time, containing hour, minute and second, use Date and DateFormatter . Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only time (hour, minute and second).


1 Answers

Swift 5.0 / 4.0 / 3.0

let hour = Calendar.current.component(.hour, from: Date()) 

 

Or, if you're interested in 12 hour AM/PM date format, then use NSDateFormatter

let formatter = DateFormatter() formatter.dateFormat = "hh a" // "a" prints "pm" or "am" let hourString = formatter.string(from: Date()) // "12 AM" 

If you want minutes, seconds and others, do as following

let date = Date() // save date, so all components use the same date let calendar = Calendar.current // or e.g. Calendar(identifier: .persian)  let hour = calendar.component(.hour, from: date) let minute = calendar.component(.minute, from: date) let second = calendar.component(.second, from: date) 

Check out available components on Apple docs:

.era, .year, .month, .day, .hour, .minute, .second, .weekday, .weekdayOrdinal, .quarter, weekOfMonth, .weekOfYear, .yearForWeekOfYear, .nanosecond, .calendar, .timezone 

Swift 2.0

let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate()) 

Swift 1.0

let hour = NSCalendar.currentCalendar().component(.CalendarUnitHour, fromDate: NSDate()) 
like image 151
average Joe Avatar answered Sep 23 '22 11:09

average Joe