-3

I receive a timestamp from a JSON request, and I want to format it to a user-friendly format. Both the input, as the desired output are of type 'String'.

The format of the input timestamp is: 2020-03-07T12:18:26.347Z

Using the following code, I try to convert it to the desired format. But it will just output the value of Date(), indicating that the output of formatter.date(from: date) is nil.

What am I missing?

func convertDate(date: String) -> String {

    let formatter = DateFormatter()
    formatter.dateFormat = "d-M-y, HH:mm"

    let convertedDate = formatter.date(from: date) ?? Date()

    return formatter.string(from: convertedDate)

}
Asperi
  • 228,894
  • 20
  • 464
  • 690
unequalsine
  • 184
  • 2
  • 10

2 Answers2

1

Your dateFormat doesn't match the format of your input string. You want something like:

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
zpasternack
  • 17,838
  • 2
  • 63
  • 81
0

After struggling with it for hours, this answer, together with the date format information found here, I figured it out. I did previously not describe to the dateformatter how the input string would look.

func convertDate(date: String) -> String {

    let dateFormatter = DateFormatter()

    // This is important - we set our input date format to match our input string
    // if the format doesn't match you'll get nil from your string, so be careful
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

    //`date(from:)` returns an optional so make sure you unwrap when using.
    let dateFromString: Date? = dateFormatter.date(from: date)

    let formatter = DateFormatter()
    formatter.dateFormat = "dd-MM-yyyy, HH:mm"

    //Using the dateFromString variable from before.
    let stringDate: String = formatter.string(from: dateFromString!)

    return stringDate

}
unequalsine
  • 184
  • 2
  • 10