Converting [string] to string

how can i append dateFormat "dMMM hh" into an array of dates

let arrx = DateFormatter()

arrx.dateFormat = "dMMM hh"

var date = Date()


while im appending in different methods getting an errors like 1.Cannot convert value of type 'Date' to expected argument type 'String' and

2.Cannot convert value of type [string] to expected argument type 'String'

Replies

It is not clear enough what you are trying to do.


Please show your code which produces `Cannot convert value of type 'Date' to expected argument type 'String'` or `Cannot convert value of type [string] to expected argument type 'String'`.


Generally if you want to add something to an Array of type [String], the added element also needs to be a String.

var stringArray: [String] = []

let arrx = DateFormatter()
arrx.dateFormat = "dMMM hh"
//... you may need more to setup DateFormatter
var date = Date()

//append dateFormat "dMMM hh" into an array of String
stringArray.append("dMMM hh")
//append Date, convert the Date to String
stringArray.append(arrx.string(from: date))


If this is not what you intend, you may need to describe your issue more precisely. Including examples of input, and desired output for each input, in addition, when discussing about errors, you should also show the exact code which caused the errors.

Regardless of the specific compile-time issue you’re having here, I must warn you about using fixed-format date strings with

DateFormatter
. This is unlikely to produce the results you want. To learn more about why, read QA1480 NSDateFormatter and Internet Dates.

In situations like this, where you want to configure a date formatter to work with a specific set of components, use

dateFormat(fromTemplate:options: locale:)
or the newer convenience method
setLocalizedDateFormatFromTemplate(_:)
. For example:
let df = DateFormatter()
df.setLocalizedDateFormatFromTemplate("dMMM")
let nowStr = df.string(from: Date())
print(nowStr)

prints

May 9
for US users and
9 May
for UK users.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"