如何在swift(ios)中将字符串格式的日期转换为另一种字符串格式[重复]

Posted

技术标签:

【中文标题】如何在swift(ios)中将字符串格式的日期转换为另一种字符串格式[重复]【英文标题】:How to convert date of string format to another string format in swift(ios) [duplicate] 【发布时间】:2020-01-24 09:58:55 【问题描述】:

我有一个字符串“2020-01-01T00:00:00”。我该如何在swift(ios)中将它转换为另一个格式“01-Jan-2020”的字符串?

转换是从StringString

【问题讨论】:

使用DateFormatterString 转换为Date 并使用另一个DateFormatter 将其转换为您想要的String 格式 - 所以您实际上有两个问题,这两个问题之前都已经回答过很多次了——我建议先尝试一下,如果你仍然有问题,就你尝试过的工作发布一个问题 【参考方案1】:
let inputDate = "2020-01-01T00:00:00"

let dateFmt = DateFormatter()
dateFmt.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"

if let date = dateFmt.date(from: inputDate) 
    dateFmt.dateFormat = "dd-MMM-yyyy"
    print(dateFmt.string(from: date))

【讨论】:

【参考方案2】:

试试下面的函数

func convertDateFormater(_ date: String, current_formate : String, expected_formate: String) -> String
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = current_formate
    let date = dateFormatter.date(from: date)
    dateFormatter.dateFormat = expected_formate
    return  dateFormatter.string(from: date!)

【讨论】:

以上是关于如何在swift(ios)中将字符串格式的日期转换为另一种字符串格式[重复]的主要内容,如果未能解决你的问题,请参考以下文章

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

在 Swift 中将字符串转换为日期 [重复]

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

无法在 Swift 中将日期格式转换为显示日期

如何在IOS中将日期格式化为字符串,如“一天前”、“分钟前”?

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