How to get the hour of the day with Swift? How to get the hour of the day with Swift? ios ios

How to get the hour of the day with Swift?


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 datelet 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())


Swift 3:

let date = Date()// Aug 25, 2017, 11:55 AMlet calendar = Calendar.currentlet hour = calendar.component(.hour, from: date) //11let minute = calendar.component(.minute, from: date) //55let sec = calendar.component(.second, from: date) //33let weekDay = calendar.component(.weekday, from: date) //6 (Friday) 

Get any of component available from the API below

public enum Component {    case era    case year    case month    case day    case hour    case minute    case second    case weekday    case weekdayOrdinal    case quarter    case weekOfMonth    case weekOfYear    case yearForWeekOfYear    case nanosecond    case calendar    case timeZone}

Swift 2:

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

This could be enough :

let currentDate = NSDate() // You can input the custom as well let calendar = NSCalendar.currentCalendar()let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate:  currentDate)let currentHour = components.hour // You can play around with the ""components""


If you want the current hour in a String, this is as short and readable I could think of.

let formatter = NSDateFormatter()formatter.dateFormat = "HH"let timeString = formatter.stringFromDate(NSDate())