Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting time of the day Swift Morning/Afternoon/Evening/Any time

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.

like image 544
Andrius Steponavičius Avatar asked Sep 18 '15 09:09

Andrius Steponavičius


People also ask

What time in the morning in the afternoon or in the evening?

Morning is generally considered the time range from 6 am to noon. The afternoon is from noon to 6 pm. The evening is from 6 pm to midnight.

How do I get the current date and time in Swift 5?

To get the current time in Swift: Choose a date. Grab the hour, minute, and the second using calendar's time components. Display the time by grouping the time components.


2 Answers

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.

like image 85
vadian Avatar answered Sep 22 '22 12:09

vadian


Here's how I solved the problem using Swift 2. First, I used this article to identify the various parts of the day. From there, I used a series of if/else if statements. I'm curious if someone else can do this using ranges.

//BIG PICTURE SOLUTION
//Step 1: Build a .plist or REST API service or whatever made up of different ways to describe "parts of the day" in different languages. 
//http://stackoverflow.com/questions/3910244/getting-current-device-language-in-ios
//List of Language Codes: https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
//Step 2: Get the user's local time zone
//Step 3: Calculate whether the user's local time fits within these buckets of time


import Foundation

class DayParts{
    var currentHour:Int
    var localLang:String?

    // IDEA: Build a .plist or a REST API service or whatever that simply returns a dictiontary
    let letterCodes:[String:Array<String>] = [
        "en": ["Early Morning", "Late Morning", "Early Afternoon", "Late Afternoon", "Evening", "Night"],
        "fr": ["Tôt le matin", "Tard dans la matinée", "Début d'après-midi", "Tard dans l'après-midi", "Soir", "Nuit"],
        "es": ["Mañana Temprano", "Mañana tarde", "Temprano en la tarde", "Fin de la tarde", "Anochecer", "Noche"]
    ]

    init(){
        //A. Get the current time
        let date = NSDate()
        let dateFormatter = NSDateFormatter()
            dateFormatter.dateFormat = "HH"
        //B. Get the current hour
        currentHour = Int(dateFormatter.stringFromDate(date))!
        //C. Get the current phone language
        localLang = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as? String
    }

    func now() -> String {
        if(currentHour < 08){
            return letterCodes[localLang!]![0]
        }
        else if(currentHour < 11){
            return letterCodes[localLang!]![1]
        }
        else if( currentHour < 15){
            return letterCodes[localLang!]![2]
        }
        else if( currentHour < 17){
            return letterCodes[localLang!]![3]
        }
        else if(currentHour < 21){
            return letterCodes[localLang!]![4]
        }
        else{
            return "Night"
        }
    }
}

let dayParts = DayParts().now()
like image 24
Chris M Avatar answered Sep 23 '22 12:09

Chris M