gpt4 book ai didi

swift - 将字符串转换为日期在 swift 3 中不相同

转载 作者:行者123 更新时间:2023-11-28 08:01:29 25 4
gpt4 key购买 nike

为什么?我将字符串转换为日期,输入不同的输出?

Input: 
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
dateLahir = formatter.date(from: "2017-10-05")
print("date: \(dateLahir)")

Output:
date: 2017-10-04

最佳答案

在 Swift 3 中将日期转换为字符串

class func convertDateToString(_ dateStr: String?, fromDateFormat currentFormat: String, toDateFormat newFormat: String) -> String? {

if dateStr == nil {
return nil
}

let formatter:DateFormatter = DateFormatter()
formatter.dateFormat = currentFormat
let date = formatter.date(from: dateStr!)

if date == nil {
return ""
}

formatter.dateFormat = newFormat
let newStr: String = formatter.string(from: date!)

return newStr
}

将字符串转换为日期

class func convertStringToDate(_ strDate: String, dateFormat: String) -> Date? {
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = dateFormat
formatter.timeZone = TimeZone.autoupdatingCurrent

let date = formatter.date(from: strDate)

return date;
}

关于swift - 将字符串转换为日期在 swift 3 中不相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46577459/

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