In this tutorial, you are going to see how to convert the date format from dd/MM/YYYY to YYYY-MM-dd in Swift with code examples.
There are multiple ways to convert date format for a specific date string in Swift. In this tutorial, you will be introduced to two methods that can perform our task.
Below is given the code for the first method:
import Foundation
func convertDateFormat(sourceDateString : String, sourceDateFormat : String, destinationFormat : String) -> String{
let dateFormatter = DateFormatter();
dateFormatter.dateFormat = sourceDateFormat;
if let date = dateFormatter.date(from: sourceDateString){
dateFormatter.dateFormat = destinationFormat;
return dateFormatter.string(from: date)
}else{
return ""
}
}
// Usage of the function
let dateString = "11/04/1991"
let dateFormatString = "dd/MM/yyyy"
let requiredFormatString = "yyyy-MM-dd"
let newDateFormat = convertDateFormat(sourceDateString: "11/04/1991", sourceDateFormat: "dd/MM/yyyy", destinationFormat: "yyyy-MM-dd")
print(newDateFormat)
Output:
1991-04-11
In the above program, we have created a function with the name convertDateFormat
. In this function, we just have to pass some parameters:
Now let’s convert the date format using another method:
import Foundation
extension String
{
func toDateFormat( inputDateFormat inputFormat : String, ouputDateFormat outputFormat : String ) -> String
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = inputFormat
let date = dateFormatter.date(from: self)
dateFormatter.dateFormat = outputFormat
return dateFormatter.string(from: date!)
}
}
// Usage of the function
let stringOfDate = "11/04/1991"
let requireDateFormat = stringOfDate.toDateFormat(inputDateFormat: "dd/MM/yyyy", ouputDateFormat: "yyyy-MM-dd")
print(requireDateFormat)
Output:
1991-04-11
In this program also, we have created a Swift function to convert the date format from dd/MM/yyyy to yyyy-MM-dd.
To use the function, all you need to do is just call it and pass your date as a string, the format of the date and the format of the converted date.
In the above example, the date we want to convert is 11/04/1991. After the successful conversion, we can see the date 1991-04-11 in the output.
In both of our examples, we have used the DateFormatter class. The DateFormatter class is used to convert between dates and the textual representations of dates.
Also read: Generate Random Number in Swift