Search code examples
iosswiftcocoa-touchnsdateformatterdate-formatting

How can I format date


I get a date formatted like 2015-07-15 17:12:00 +0000, but I want to display it like Jul 15 2015.

How can I do that?

Code:

func formatDate(date: String) -> String {

    if date != "" {
        var dateString = date
        dateString = dateString.substringToIndex(advance(minElement(indices(dateString)), 19))
       dateString = dateString.stringByReplacingOccurrencesOfString("", withString: " ")
        var dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
        var dateStr = dateFormatter.dateFromString(dateString)
        dateFormatter.dateStyle = NSDateFormatterStyle.MediumStyle
        var date = dateFormatter.stringFromDate(dateStr!)
        return date
    }
    else {
        return ""
    }


}

Solution

  • Your input dateFormatter string is a bit off - it does not include the time zone and uses the wrong hour pattern. The following works and finally outputs

    Jul 15 2015

    let dateStr = "2015-07-15 17:12:00 +0000"
    var dateFormatterIn = NSDateFormatter()
    dateFormatterIn.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    let date = dateFormatterIn.dateFromString(dateStr)
    
    let dateFormatterOut = NSDateFormatter()
    dateFormatterOut.dateFormat = "MMM dd yyyy"
    print(dateFormatterOut.stringFromDate(date!))
    

    For the correct date strings take a look at the unicode docs