gpt4 book ai didi

ios - 如何将字符串日期转换为 NSDate?

转载 作者:可可西里 更新时间:2023-11-01 00:36:48 25 4
gpt4 key购买 nike

我想将 2016-03-09 00:00:00 转换为 09/03/2016

我正在尝试下面的代码但打印nil

var date: [String] = ["2016-03-09 00:00:00", "2016-03-20 00:00:00"]

for i in date {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/YYYY"
let showDate = dateFormatter.dateFromString(i)
print(showDate)
}

上面的代码打印nil
请帮助我如何快速打印日期 dd/MM/YYYY 格式

最佳答案

我认为您的日期格式有误。将“dd/MM/YYYY”更改为“YYYY-MM-dd HH:mm:s”并尝试...

You have a date like "2016-03-09 00:00:00" .. so format should be "YYYY-MM-dd HH:mm:s"

for i in date {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:s"
if let showDate = dateFormatter.dateFromString(i){
print("Date with Time: \(showDate)")
dateFormatter.dateFormat = "YYYY-MM-dd"
let resultString = dateFormatter.stringFromDate(showDate)
print("final result: \(resultString)")
}
}

结果:-

Date with Time: 2016-03-09 00:00:00 +0000
final result: 2016-03-09
Date with Time: 2016-03-20 00:00:00 +0000
final result: 2016-03-20

关于ios - 如何将字符串日期转换为 NSDate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36099150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com