简体   繁体   English

快速将特定格式的字符串转换为NSDate

[英]Swift convert string with specific format to NSDate

I would like to convert these two strings to NSDate. 我想将这两个字符串转换为NSDate。

1. "2015-10-19T15:27:48.173754Z" 1. "2015-10-19T15:27:48.173754Z"

2. "2015-10-19T15:27:31Z" 2. "2015-10-19T15:27:31Z"

I tried using this function for format #1: 我尝试使用此功能的格式#1:

static func prepareDate(dateString: String)-> NSDate
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ssZ"
    let date = dateFormatter.dateFromString(dateString)
    return date
}

But it always return nil. 但是它总是返回nil。 Can someone advice what is the problem? 有人可以建议出什么问题吗?

You need to quote the T with ' marks 您需要在T加上'标记

func prepareDate(dateString: String)-> NSDate?
{
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.dateFromString(dateString)
    return date
}

Its parsing as part of the date magic formatters. 作为日期魔术格式化程序的一部分进行解析。

let test = "2015-10-19T15:27:31Z" -> "Oct 19, 2015, 4:27 PM"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM