How can you determine the hour, minute and second from NSDate class in Swift 3?
In Swift 2:
let date = NSDate()
let calendar = NSCalendar.currentCale
Swift 4
let calendar = Calendar.current
let time=calendar.dateComponents([.hour,.minute,.second], from: Date())
print("\(time.hour!):\(time.minute!):\(time.second!)")
Swift 4.2 & 5
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = Calendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date))
// *** define calendar components to use as well Timezone to UTC ***
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents([.hour, .year, .minute], from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
Swift 3.0
// *** Create date ***
let date = Date()
// *** create calendar object ***
var calendar = NSCalendar.current
// *** Get components using current Local & Timezone ***
print(calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date as Date))
// *** define calendar components to use as well Timezone to UTC ***
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!
// *** Get All components from date ***
let components = calendar.dateComponents(unitFlags, from: date)
print("All Components : \(components)")
// *** Get Individual components from date ***
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("\(hour):\(minutes):\(seconds)")
This might be handy for those who want to use the current date in more than one class.
extension String {
func getCurrentTime() -> String {
let date = Date()
let calendar = Calendar.current
let year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"
return realTime
}
}
Usage
var time = ""
time = time.getCurrentTime()
print(time) // 1900-12-09-12-59
In Swift 3 you can do this,
let date = Date()
let hour = Calendar.current.component(.hour, from: date)