将字符串转换为日期与swift 3中的不同

时间:2017-10-05 03:36:06

标签: swift

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

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

Output: 
date: 2017-10-04

1 个答案:

答案 0 :(得分:0)

在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;
}