Get the day of the week from a date taken from sqlite swift

1

I'm doing a function in swift that you formatted me on a date I get from the database sqlite and display it with the following format: Miércoles, 07 de septiembre de 2016 a las 10:03:56 .

I have almost everything, I just need to be able to get the name of the day of the week, I do not know how to do it.

My code:

func formatFechaHuman(fecha: String) -> String {
        var nuevaFecha = String()
        let arrayString = fecha.componentsSeparatedByString(" ")
        let hora = arrayString[1]
        let partesFecha = arrayString[0]
        let componentesFecha = fecha.componentsSeparatedByString("-")
        let year = componentesFecha[0]
        let month = componentesFecha[1]
        let day = componentesFecha[2]
        var mesFecha = ""

        switch (month) {
            case "01":
                mesFecha = "Enero"
                break

            case "02":
                mesFecha = "Febrero"
                break

            case "03":
                mesFecha = "Marzo"
                break

            case "04":
                mesFecha = "Abril"
                break

            case "05":
                mesFecha = "Mayo"
                break

            case "06":
                mesFecha = "Junio"
                break

            case "07":
                mesFecha = "Julio"
                break

            case "08":
                mesFecha = "Agosto"
                break

            case "09":
                mesFecha = "Septiembre"
                break

            case "10":
                mesFecha = "Octubre"
                break

            case "11":
                mesFecha = "Noviembre"
                break

            case "12":
                mesFecha = "Diciembre"
                break

            default:
                mesFecha = ""
                break
        }

        nuevaFecha = ", " + month + " de " + mesFecha + " de " + year + " a las " + hora

        return nuevaFecha
    }
    
asked by 07.09.2016 в 10:35
source

1 answer

0

There are several ways to do it. For me the best is to use NSDateComponents and using weekday . If we define the function getDayOfWeek :

func getDayOfWeek(today:String)->Int {

    let formatter  = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd"
    let todayDate = formatter.dateFromString(today)!
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
    let weekDay = myComponents.weekday
    return weekDay
}

And you basically call it that:

let weekday = getDayOfWeek(fecha)

This returns an int that goes from 1 to 7 (and I think 1 = Sunday) so according to the int that returns the function:

  

1 - Sunday

     

2 - Monday

     

3 - Tuesday

     

4 - Wednesday

     

5 - Thursday

     

6 - Friday

     

7 - Saturday

    
answered by 07.09.2016 / 10:44
source