0

In my scenario, I am trying to convert date time string one format to another format 26 Nov, 2019 - 2:53 AM to yyyy-MM-dd h:mm:ss. How to cover the format?

Below Code Returning Empty

let dateString = "26 Nov, 2019 - 2:53 AM"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm a"
dateFormatter.locale = Locale.init(identifier: "en_GB")
let dateres = dateFormatter.date(from: dateString)
print(dateres)

2 Answers 2

3
extension String {
func convertToDateFormate(current: String, convertTo: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = current
    guard let date = dateFormatter.date(from: self) else {
        return self
    }
    dateFormatter.dateFormat = convertTo
    return  dateFormatter.string(from: date)
}
}

convert to required formate as

let dateString = "12-10-2019"
let convertedDate = dateString.convertToDateFormate(current: "dd-MM-YYYY", convertTo: "YYYY-MM-dd")
Sign up to request clarification or add additional context in comments.

Comments

0

Try This

Step 1:- Put this function on your class file

func convertDate(date: String, dateFormat : String, convertFormat : String) -> String {
        let datetimeFormatOriginal = DateFormatter()
        datetimeFormatOriginal.dateFormat = dateFormat

        let convertedFormat = DateFormatter()
        convertedFormat.dateFormat = convertFormat

        if date == "" || date == "-" {
            return "-"
        }
        else {
            return convertedFormat.string(from: datetimeFormatOriginal.date(from: date)!)
        }
    }

Step:- 2 Now using this function convert date

let convertedDate = convertDate(date: "26 Nov, 2019 - 2:53 AM", dateFormat: "dd MMM, yyyy - HH:mm aa", convertFormat: "yyyy-MM-dd hh:mm a")

print(convertedDate)

OUTPUT

"2019-11-26 12:53 AM"

1 Comment

Most Well-Come My Pleasure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.