ios 如何在 Swift 中将日期转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50195261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:41:59  来源:igfitidea点击:

How to convert Date to String in Swift

iosswift

提问by John Martin

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:

我试图调用一个函数,一个参数是当前时间和日期,另一个是文件名,它们都是字符串。如何转换Date()为字符串。我试过:

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

but it gave me error:

但它给了我错误:

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

无法将“日期”类型的值转换为预期的参数类型“字符串”

回答by Yimin Rong

Something like this:

像这样的东西:

let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd hh:mm:ss"
let now = df.stringFromDate(Date())
writeToFile(content: now, fileName: "jm.txt")

回答by Danziger

You need to use DateFormatterfor that:

您需要为此使用DateFormatter

let formatter = DateFormatter()

formatter.dateFormat = "yyyy-MM-dd"

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