本地化问候消息的问题

use*_*428 0 nslocale swift

我刚刚完成了我的第一个应用程序并且已经在本地化了不同的功能.我的应用程序中有一个功能,我不确定是否可以进行本地化.

基本上,当用户打开我的应用程序时,会收到一条消息,上面写着"下午好","早上好"或"晚上好".我创建了一些代码来检查时间的前缀,以决定显示什么消息,但是由于不同的国家/地区格式化时间不同,我不确定如何将其本地化.

我是否必须弄清楚它确实在哪些国家工作,并添加一个if语句来决定该应用是否可以显示此问候语?否则根据他们的名字显示问候语?

这是我的代码:

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"
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 6

您不应使用本地化时间字符串来确定一天中的时间.

使用NSCalendarNSDateComponents:

let now = NSDate()
let cal = NSCalendar.currentCalendar()
let comps = cal.components(.CalendarUnitHour, fromDate: now)
let hour = comps.hour
Run Code Online (Sandbox Code Playgroud)

现在hour是0到23范围内的整数.

var currentTimeOfDay = ""
switch hour {
case 0 ... 12:
    currentTimeOfDay = "morning"
case 13 ... 17:
    currentTimeOfDay = "afternoon"
default:
    currentTimeOfDay = "evening"
}
Run Code Online (Sandbox Code Playgroud)