Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Date to String in Swift [duplicate]

Tags:

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'

like image 555
John Martin Avatar asked May 06 '18 00:05

John Martin


2 Answers

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") 
like image 135
Yimin Rong Avatar answered Sep 22 '22 21:09

Yimin Rong


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") 
like image 27
Danziger Avatar answered Sep 22 '22 21:09

Danziger