Reputation: 125
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)
Upvotes: 0
Views: 1744
Reputation: 1448
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"
Upvotes: 0
Reputation: 420
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")
Upvotes: 3