Junior Sanches
Junior Sanches

Reputation: 51

Transform date string to another format in Swift

I'm a beginner in Swift and I'm getting a date from a JSON snippet in string format, yyyy-MM-dd. For example:

2017-09-20

How do I display it in dd/MM/yyyy format?

20/09/2017

I am trying the following:

var dateString =  item["data"] as! String
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = dateFormatter.date(from: dateString)
print(date)

But my result when printed is null.

Upvotes: 2

Views: 2998

Answers (2)

Naveed Ahmad
Naveed Ahmad

Reputation: 6737

Helper Method for changing date format to another format:

class Helper {

static func changeDateFormat(dateString: String, fromFormat: String, toFormat: String) ->String {
    let inputDateFormatter = DateFormatter()
    inputDateFormatter.dateFormat = fromFormat
    let date = inputDateFormatter.date(from: dateString)

    let outputDateFormatter = DateFormatter()
    outputDateFormatter.dateFormat = toFormat
    return outputDateFormatter.string(from: date!)
}
}

Now, Where you want to use this method, just call helper class with the required params

println(Helper.changeDateFormat(dateString: "2017-09-20", fromFormat: "yyyy-MM-dd", toFormat: "yyyy/MM/dd"))

Upvotes: 5

Matthew Crumley
Matthew Crumley

Reputation: 102725

When you're converting the string to a date, you need the dateFormat to match the format of the string: yyyy-MM-dd. Then you would use a second DateFormatter with the output format to display it.

var dateString =  item["data"] as! String
let inputDateFormatter = DateFormatter()
inputDateFormatter.dateFormat = "yyyy-MM-dd"
let date = inputDateFormatter.date(from: dateString)

let outputDateFormatter = DateFormatter()
outputDateFormatter.dateFormat = "dd/MM/yyyy"
print(outputDateFormatter.string(from: date))

If this code is going to be running more than a few times, you should probably reuse the DateFormatter instances instead of recreating them each time, because it's an expensive class to create.

Upvotes: 3

Related Questions