Swift 2.0 字符串转 NSDate

Swift 2.0 String to NSDate

您好,我从 Datepicker 获取我的日期,该日期被保存到一个字符串中,然后上传到 Firebase。然后将字符串接收到 phone。问题是我想在检索时将此字符串转换为 NSDate。

这就是我从日期选择器中获取字符串的方式

func datePickerChanged(datePicker:UIDatePicker){
    var dateFormatter = NSDateFormatter()

    dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

    var strDateFrom = dateFormatter.stringFromDate(datePicker.date)
    fromDate = strDateFrom
    print(fromDate)}

当我检索日期时,我将它作为字符串获取,这就是打印

print(self.membershipActiveTo)

这是打印日志 2016 年 5 月 11 日,2:35 下午

下面是我尝试转换为字符串的代码行,但它只有 returns nil

let strDate = self.membershipActiveTo // "2015-10-06T15:42:34Z"
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm"
        print ( dateFormatter.dateFromString( strDate ) )

使用日期时需要考虑一些事项,其中之一就是如何以一致的格式存储日期,以便轻松处理不同用途。在你的情况下,你可能想按日期排序,如果数据是这样存储的

2016 年 5 月 11 日,2:35 下午

它不会被排序。因此,需要一种不同的格式,这是一个可能的例子

20160511143500

下面是一些操作日期的代码:

将格式正确的日期写入 Firebase

let d = NSDate()

//create a custom date string & save in firebase
let dateFormatterCustom = NSDateFormatter()
dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"

let customDateString = dateFormatterCustom.stringFromDate(d)
print(customDateString) //prints "20160511023500" just for testing

let timesRef = self.myRootRef.childByAppendingPath("time_test")
let thisTimeRef = timesRef.childByAutoId()
let timeChildRef = thisTimeRef.childByAppendingPath("timestamp")

timeChildRef.setValue(customDateString)

Firebase 现在有这个

time_test  
 -KFerAcANQv4pN1Pp4yW
    timestamp: "20160418033309"

然后从 Firebase 读取:

    let timesRef = self.myRootRef.childByAppendingPath("time_test")

    timesRef.observeEventType(.ChildAdded, withBlock: { snapshot in

        let timeStamp = snapshot.value.objectForKey("timestamp") as! String
        print(timeStamp) //still looks like 20160418033309

        let shortDateString = self.timeStampToDateString(timeStamp)
        print(shortDateString) //prints 4/18/16, 3:33 AM

    })

以及将时间戳样式字符串转换为人类可读字符串的函数

func timeStampToDateString(stamp: String) -> String {

    //create a custom date string & create a date object from it
    let dateFormatterCustom = NSDateFormatter()
    dateFormatterCustom.locale = NSLocale(localeIdentifier: "US_en")
    dateFormatterCustom.dateFormat = "yyyyMMddhhmmss"

    let d = dateFormatterCustom.dateFromString(stamp)!

    //create a short date style string and format the string
    let dateFormatterShortStyle  = NSDateFormatter()
    dateFormatterShortStyle.dateStyle = NSDateFormatterStyle.ShortStyle
    dateFormatterShortStyle.timeStyle = NSDateFormatterStyle.ShortStyle

    let dateString = dateFormatterShortStyle.stringFromDate(d)

    return dateString
}

此示例中有很多额外代码,因此可以大大缩短,但我想保留所有步骤。