-1

I'm using the Nasa API. It returns dates in raw string format: "date": "2022-01-15" (YYYY-MM-DD)

How do I format it to something like Jan 15th, 2022 using DateFormatter and display it in a SwiftUI Text View?

private var dateFormatter = DateFormatter().configure {
    $0.dateFormat = "yyyy-MM-dd"
    $0.dateStyle = .medium
    $0.doesRelativeDateFormatting = true
    $0.locale = .current
    $0.timeStyle = .medium
}

private var formattedDate: String {
    guard let date = dateFormatter.date(from: apod.date) else { return "No date" }
    return dateFormatter.string(from: date)
}

// Call site
Text(formattedDate)

It gives me "No date" on all items

Marcus Ziadé
  • 650
  • 2
  • 7
  • 17

1 Answers1

0

Using a separate formatter did the trick

var dateFormatter = DateFormatter().configure {
    $0.dateFormat = "yyyy-MM-dd"
}

var dateFormatterOutput = DateFormatter().configure {
    $0.dateStyle = .full
}

private var formattedDate: String {
    guard let date = dateFormatter.date(from: apod.date) else { return "No date" }
    return dateFormatterOutput.string(from: date)
}
Marcus Ziadé
  • 650
  • 2
  • 7
  • 17
  • This is seriously error prone. You will have too many issues with this code. – Leo Dabus Jan 22 '22 at 12:06
  • Btw if can improve your configure method making a generic initializer that takes a predicate https://stackoverflow.com/a/64414890/2303865 – Leo Dabus Jan 22 '22 at 12:12
  • @LeoDabus Thanks for your reply, but it's entirely useless unless you explain why – Marcus Ziadé Jan 23 '22 at 09:11
  • 1
    You are not setting the date formatter calendar. If the user device is using Buddhist calendar it will parse a date with 500+ years offset – Leo Dabus Jan 23 '22 at 09:13
  • 1
    Also not setting the calendar would result in failing to parse dates where there is no midnight if you pass a daylight savings transition date because the date string has no time. It will try to generate a midnight date but it doesn’t exist it so returns nil. If you set the calendar it will return the first date for that locale. Usually 1am. – Leo Dabus Jan 23 '22 at 09:17
  • 1
    Also when parsing fixed date format you should always set the locale to “en_US_POSIX”. This will avoid the date formatter reflecting the device locale and settings – Leo Dabus Jan 23 '22 at 09:20
  • 1
    Also be careful while parsing a date without timezone. The timezone you need to set the date formatter will depend on the context. If you are parsing a date of a bill to be paid it should use the timezone of the locale where the user has to pay it (fixed timezone). It could also be the timezone of the user (that’s how you have now) or the backend (server) or simply UTC timezone. – Leo Dabus Jan 23 '22 at 09:25
  • https://stackoverflow.com/a/32408916/2303865 – Leo Dabus Jan 23 '22 at 09:30