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
==> Getting iOS device current time:-
print(" ---> ",(Calendar.current.component(.hour, from: Date())),":",
(Calendar.current.component(.minute, from: Date())),":",
(Calendar.current.component(.second, from: Date())))
output: ---> 10 : 11: 34
For best useful I create this function:
func dateFormatting() -> String {
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
let mydt = dateFormatter.string(from: date).capitalized
return "\(mydt)"
}
You simply call it wherever you want like this:
print("Date = \(self.dateFormatting())")
this is the Output:
Date = Monday 15 October 2018 - 17:26:29
if want only the time simply change :
dateFormatter.dateFormat = "HH:mm:ss"
and this is the output:
Date = 17:27:30
and that's it...
In Swift 3.0 Apple removed 'NS' prefix and made everything simple. Below is the way to get hour, minute and second from 'Date' class (NSDate alternate)
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let seconds = calendar.component(.second, from: date)
print("hours = \(hour):\(minutes):\(seconds)")
Like these you can get era, year, month, date etc. by passing corresponding.
let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)
Swift 5+
extension Date {
func get(_ type: Calendar.Component)-> String {
let calendar = Calendar.current
let t = calendar.component(type, from: self)
return (t < 10 ? "0\(t)" : t.description)
}
}
Usage:
print(Date().get(.year)) // => 2020
print(Date().get(.month)) // => 08
print(Date().get(.day)) // => 18
let date = Date()
let units: Set<Calendar.Component> = [.hour, .day, .month, .year]
let comps = Calendar.current.dateComponents(units, from: date)