let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let localeIdentifier = "ar_AE"
dateFormatter.locale = Locale(identifier: localeIdentifier)
if let date = dateFormatter.date(from: "2022-12-26") {
dateFormatter.dateFormat = "dd MMM YYYY"
let displayDate = dateFormatter.string(from: date)
print(displayDate) // "26 ديسمبر 2023"
}
Converted date is one year ahead of the actual date. This issue occurs only with specific dates ranging from 26-Dec-2022 to 31st-Dec-2022, when Arabic locale is selected and on IOS 16.0 and above devices.
There are three problems here. The first is that you’re confusing yyyy with YYYY. The latter gives you the year in the week-of-year calendar, which can be out of sync with the standard calendar at the start and end of the year.
A much bigger problems is that you’re using DateFormatter to parse fixed-format dates without pinning the locale to en_US_POSIX. That can yield all sorts of weird issues. QA1480 NSDateFormatter and Internet Dates discusses that in detail.
Finally, parsing a date without a time is tricky. See Parsing Dates Without Times.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"