I am just finishing up my first app and have been localising different features. I have one feature in my app that I am not sure if I can localise or not.
Basically, when users open my app, they are greeted with a message that says 'good afternoon', 'good morning' or 'good evening'. I created some code that checks the prefix of the time to decide what message to display, however since different countries format time differently, I'm not sure how I can localise this.
Will I have to figure out the countries that it does work in and add an if statement that decides whether the app can display this greeting or not? Otherwise display a greeting based on their name instead?
Here is my code:
var date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
let time = dateFormatter.stringFromDate(date)
var currentTimeOfDay = ""
if time.hasPrefix("0") {
currentTimeOfDay = "morning"
} else if time.hasPrefix("10") {
currentTimeOfDay = "morning"
} else if time.hasPrefix("11") {
currentTimeOfDay = "morning"
} else if time.hasPrefix("12") {
currentTimeOfDay = "morning"
} else if time.hasPrefix("13") {
currentTimeOfDay = "afternoon"
} else if time.hasPrefix("14") {
currentTimeOfDay = "afternoon"
} else if time.hasPrefix("15") {
currentTimeOfDay = "afternoon"
} else if time.hasPrefix("16") {
currentTimeOfDay = "afternoon"
} else if time.hasPrefix("17") {
currentTimeOfDay = "afternoon"
} else if time.hasPrefix("18") {
currentTimeOfDay = "evening"
} else if time.hasPrefix("19") {
currentTimeOfDay = "evening"
} else if time.hasPrefix("2") {
currentTimeOfDay = "evening"
}
You should not use a localized time string to determine the time of the day.
Use NSCalendar
and NSDateComponents
:
let now = NSDate()
let cal = NSCalendar.currentCalendar()
let comps = cal.components(.CalendarUnitHour, fromDate: now)
let hour = comps.hour
Now hour
is an integer in the range 0 ... 23.
var currentTimeOfDay = ""
switch hour {
case 0 ... 12:
currentTimeOfDay = "morning"
case 13 ... 17:
currentTimeOfDay = "afternoon"
default:
currentTimeOfDay = "evening"
}