在Swift中将字符串转换为NSDate

时间:2016-05-10 13:18:43

标签: ios swift nsdate nsdateformatter

我在Swift中将字符串转换为NSDate时遇到问题。我的日期字符串采用以下格式:

2016-05-06T14:07:23.430Z

我有一个函数来返回格式化的日期字符串,如下所示,传递给函数的日期字符串采用上面显示的格式:

private func formatDate(theDate:String?) -> String {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yy H:mm"
    let actualDate = dateFormatter.dateFromString(theDate!) //always produces nil
    let formattedDate = dateFormatter.stringFromDate(actualDate!)
    return formattedDate
}

当尝试从传递给函数的字符串中获取日期对象时,日期对象始终为nil。有人可以帮忙解决这个问题吗?谢谢!

3 个答案:

答案 0 :(得分:3)

看到这个答案:

let myDateString = "2016-05-06T14:07:23.430Z"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ss.SSS'Z"
let dateFromString = dateFormatter.dateFromString(myDateString)

let dateFormatter1  = NSDateFormatter()
dateFormatter1.dateFormat = "MM-dd-yy H:mm"
let getDate =  dateFormatter1.stringFromDate(dateFromString!)

print(getDate)

您的输出:

enter image description here

答案 1 :(得分:2)

let strDate = "2016-05-06T14:07:23.430Z"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
let date = dateFormatter.dateFromString(strDate)

答案 2 :(得分:1)

您使用了错误的DateFormat。您不应该为输入日期和输出日期使用相同的NSDateFormatter

试一试:yyyy-dd-MM'T'HH:mm:ss.SSS'Z'输入。这是一个完全有效的解决方案:

func formatDate(theDate: String?) -> String {

    let inputDateFormatter = NSDateFormatter()
    inputDateFormatter.dateFormat = "yyyy-dd-MM'T'HH:mm:ss.SSS'Z'"
    let outputDateFormatter = NSDateFormatter()
    outputDateFormatter.dateFormat = "MM-dd-yy H:mm"

    let actualDate = inputDateFormatter.dateFromString(theDate!)
    let formattedDate = outputDateFormatter.stringFromDate(actualDate!)
    return formattedDate
}

formatDate("2016-05-06T14:07:23.430Z") // returns 06-05-16 14:07