Swift如何转换日期格式[重复]

Posted

技术标签:

【中文标题】Swift如何转换日期格式[重复]【英文标题】:Swift how to convert date format [duplicate] 【发布时间】:2020-03-11 15:49:27 【问题描述】:

我有一个日期类型的日期,格式为“yyyy-MM-dd HH:mm:ss”,我想将其转换为“yyyy-MM-dd”。我不确定如何实现这一点,因为日期是 Date 类型。

例子:

let dateComponents: Date? = dateFormatterGet.date(from: "2019-03-11 17:01:26")

需要的输出:

格式类型为“yyyy-MM-dd”的日期对象

It is important to note that I have only date objects and no string.

【问题讨论】:

删除第 10 个字符之后的所有内容 ... 【参考方案1】:

您有一个字符串类型的日期,而不是日期。

您使用一个 DateFormatter 将其转换为 Date(检查 DateFormatter 是否返回 nil)。

然后您使用另一个 DateFormatter 将 Date 转换为字符串。

请不要使用“dateComponents”作为变量名。您永远不会在代码中触摸日期组件。而且您不需要指定类型,只需“let date = ...”或更好的“if let date = ...”检查零。

【讨论】:

【参考方案2】:

你可以这样使用:

        let now = Date().UTCToLocalDateConvrt(format: "yyyy-MM-dd HH:mm:ss",convertedFormat : "yyyy-MM-dd")

把下面的函数放在日期扩展类中:

extension Date 
    func UTCToLocalDateConvrt(format: String,convertedFormat: String) -> Date 
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
            let timeStamp = dateFormatter.string(from: self)
            dateFormatter.dateFormat = convertedFormat
            guard let date = dateFormatter.date(from: timeStamp)else
                return Date()
            
            return date
        

【讨论】:

【参考方案3】:
func formatDate(yourDate: String) -> String  //  "yyyy-MM-dd HH:mm:ss"
    let dateFormatterGet = DateFormatter()
    dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss" // here you can change the format that enters the func

    let dateFormatterPrint = DateFormatter()
    dateFormatterPrint.dateFormat = "yyyy-MM-dd" // here you can change the format that exits the func

    if let date = dateFormatterGet.date(from: yourDate) 
        return dateFormatterPrint.string(from: date)
     else 
        return nil
    

像这样使用它:

formatDate(yourDate: "2019-03-11 17:01:26")

它会返回一个可选的字符串,可以是 nil,确保你是安全的打开它(如果 let ,guard let)

根据link回答

【讨论】:

我的日期是 Date 类型,所以这个 ``` formatDate(yourDate: String)```应该接受 Date 类型的对象而不是字符串

以上是关于Swift如何转换日期格式[重复]的主要内容,如果未能解决你的问题,请参考以下文章

Swift 日期格式化程序错误地转换/创建日期/字符串 [重复]

如何在 Swift 中将此日期字符串格式“2018-03-30T14:36:10.093”格式化为日期 [重复]

swift - 如何将日期从上午/下午转换为 24 小时格式

在swift 3中将字符串转换为日期类型[重复]

如何使用php将日期格式转换为日期时间格式[重复]

iOS Swift:当字符串包含时区缩写时,如何将特定的日期字符串格式转换为日期对象?