1

I have string, in that it contains date ("2018-05-10T13:00:00"). But, I want date format as "MMM dd, yyyy". So, I have written code as below.

func convertDateStringToDate(longDate: String) -> String{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "MMM dd, yyyy"
    let date = dateFormatter.date(from: longDate)

    if date != nil {

        let formatter = DateFormatter()
        formatter.dateStyle = .short
        let dateShort = formatter.string(from: date!)

        return dateShort

    } else {

        return longDate
    }
}

and calling like following

let dateFormattedString = convertDateStringToDate(longDate: (valuesDict.value(forKey: "dateValue") as? String)!)

But, its printing again original value, instead of updated format.

"2018-05-10T13:00:00"

Any suggestions?

4 Answers4

3

The line let date = dateFormatter.date(from: longDate) would return nil because the dateFormatter is expecting the date string to be in MMM dd,yyyy format. So when you use if date != nil check, it goes into the else part.

What you need instead is to first convert the date string to date using the right format. Then convert it back to string using another format.

Something like this would do the job

func convertDateStringToDate(longDate: String) -> String{
    let longDateFormatter = DateFormatter()
    longDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    if let date = longDateFormatter.date(from: longDate) {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMM dd, yyyy"
        return dateFormatter.string(from: date)
    } else {
        return longDate
    }
}
Malik
  • 3,763
  • 1
  • 22
  • 35
1
func formatDate(dateString: String)-> String{
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
    if let formattedDate = dateFormatter.date(from: dateString) {
        dateFormatter.dateFormat = "MMM dd, yyyy"
         return dateFormatter.string(from: formattedDate)
    }
    return dateString
}

Just pass the string and get desired format output string.

Note: This will work only for the format mentioned in the question.

kashifasif
  • 172
  • 11
0

You need to set convert string->date in correct format and then convert back date to desired format string.

 let dateFormatter = DateFormatter()
 dateFormatter = "yyyy-MM-dd'T'HH:mm:ss"
 if let date = dateFormatter.date(from: longDate) {

    dateFormatter.dateFormat = "MMM dd, yyyy"
    return dateFormatter.string(from: date)
 }
Mahendra
  • 8,448
  • 3
  • 33
  • 56
0

You are doing wrong what you did dateFormatter.dateFormat = "MMM dd, yyyy" but you need to set dateFormatter which is your origin date..so as from now you just need to set "yyyy-MM-dd'T'HH:mm:ss" and for getting date as your desire