2

I'm trying to format a date : 2017-10-18T20:32:35.684-05:00 to return date and time. I've created some formatters along with functions that use those formatters:

var currentFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd-HH:mm:ss.SSS"
        formatter.locale = Locale.current
        return formatter
    }

   var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd MMMM"
        formatter.locale = Locale(identifier: "es_MX")
        return formatter
    }

    var timeFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        formatter.locale = Locale(identifier: "en_US_POSIX")
        return formatter
    }

func getTimeFromDate(dateString:String, stringFormatter:DateFormatter, currentFormatter: DateFormatter) -> String {
    let currentDate = stringFormatter.date(from: dateString)

    print(currentDate)//returns nil
    if let formattedDate = currentDate {
        return  currentFormatter.string(from:formattedDate)
    }else {
        return ""
    }
}

func getMexicanLocalizedStringFromDate(date: String) -> String?{
    let currentDate = self.currentFormatter.date(from: date)
    print(currentDate)//returns nil
    if let formattedDate = currentDate {
        return self.dateFormatter.string(from:formattedDate)
    }else {
        return nil
    }
}

This is how the functions are used:

   if let date = self.date {
                print(date)//This returns proper date
                let time = getTimeFromDate(dateString: date, stringFormatter: currentFormatter, currentFormatter: timeFormatter)
                print(time)
                if let monthDay = getMexicanLocalizedStringFromDate(date: date){
                    print(monthDay)
                    cell.dateLabel.text = "\(monthDay), \(time)h"
                    print( cell.dateLabel.text)
                }}

I'm not sure whenever I use the formatter it returns nil. Any help is appreciated!

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • The format `yyyy-MM-dd-HH:mm:ss.SSS` does not match the string `2017-10-18T20:32:35.684-05:00`. – rmaddy Oct 27 '17 at 21:24
  • @rmaddy what would be the proper format? I know there is T in it but not sure how to convert – SwiftyJD Oct 27 '17 at 21:25
  • 1
    Unrelated but you have a lot of open questions with answers. You should go back and accept the best answer in cases where one of the answers solved a given question, or you should provide feedback to answers where needed so the question can get a final answer worth accepting. – rmaddy Oct 27 '17 at 21:33
  • Check this resource for additional help: http://nsdateformatter.com – Maksym Musiienko Oct 27 '17 at 21:44
  • @rmaddy yes, I plan on going through my questions, thanks for reminding me – SwiftyJD Oct 27 '17 at 21:49

0 Answers0