Cannot call value of non-function type 'String?'

43 Views Asked by At

I am new to iOS development. I am trying to convert a date value which is in string format(2024-09-22) to 22 Sep 2024.

But I am getting:

Cannot call value of non-function type 'String?'

while doing date formatting.

I am getting this error in dateFormatter.dateFormat(from : dateString).

I have tried a below code for the formatting.

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MMM-yyyy"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
let convertedDate = dateFormatter.dateFormat(from : dateString)

Could someone help me to solve this issue?

2

There are 2 best solutions below

0
Andrew Bogaevskyi On BEST ANSWER

You first need to get Date from given String ("2024-09-22" format: "yyyy-MM-dd"). And create one more DateFormatter to convert Date to new String:

let dateString = "2024-09-22"

let dateFormatterToDate = DateFormatter()
dateFormatterToDate.dateFormat = "yyyy-MM-dd"
let date = dateFormatterToDate.date(from: dateString)

let dateFormatterFromDate = DateFormatter()
dateFormatterFromDate.dateFormat = "dd MMM yyyy"
let result = dateFormatterFromDate.string(from: date!) // 22 Sep 2024
0
vadian On

To convert the date string to another date string you have to convert it to Date and back to String, so you need an input and output format. An API dateFormat(from doesn't exist.

The default time zone is the current time zone and to get always English month names regardless of the current locale set the locale to en_US_POSIX

let dateString = "2024-09-22"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd"
if let date = dateFormatter.date(from: dateString) {
    dateFormatter.dateFormat = "dd MMM yyyy"
    let convertedDate = dateFormatter.string(from: date)
}