I am trying to find a way to get time of the day in words. Obviously there is easy way of doing it Application to Display Morning,Evening If you are ok with static words in one language. Is there a way of making it depending on Locale? NSDateComponentsFormatter doesn't seem to do the trick.
Unfortunately there is no built-in solution – NSDateFormatter's relative formatting works only on a per day base.
Get the hour with Calendar.current.component(.hour, from: Date())
and use a range switch and NSLocalizedString()
to localize the strings.
For example:
// let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate()) Swift 2 legacy
let hour = Calendar.current.component(.hour, from: Date())
switch hour {
case 6..<12 : print(NSLocalizedString("Morning", comment: "Morning"))
case 12 : print(NSLocalizedString("Noon", comment: "Noon"))
case 13..<17 : print(NSLocalizedString("Afternoon", comment: "Afternoon"))
case 17..<22 : print(NSLocalizedString("Evening", comment: "Evening"))
default: print(NSLocalizedString("Night", comment: "Night"))
}
Create a file localizable.strings
and add the localizations you need.