26

I'm trying to call a function one argument is current time and Date and other is a file name, They both are strings. How can I convert Date() to a string. I tried:

writeToFile(content: Date(), fileName: "jm.txt")

but it gave me error:

Cannot convert value of type 'Date' to expected argument type 'String'

Sulthan
  • 128,090
  • 22
  • 218
  • 270
John Martin
  • 443
  • 1
  • 4
  • 7

2 Answers2

50

Something like this:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss"
let now = df.string(from: Date())
writeToFile(content: now, fileName: "jm.txt")
Cosmin
  • 478
  • 1
  • 5
  • 16
Yimin Rong
  • 1,890
  • 4
  • 31
  • 48
16

You need to use DateFormatter, as stated in the docs:

Instances of DateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

In your case, that would look something like this:

let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd"

writeToFile(content: formatter.string(from: Date()), fileName: "jm.txt")
Danziger
  • 19,628
  • 4
  • 53
  • 83