简体   繁体   English

NSDateformatter dateFromString AnyObject

[英]NSDateformatter dateFromString AnyObject

I have an array of AnyObjects of NSDates and I am trying to convert to weekdays like (Mon, Tue, Wed..) 我有NSDates的AnyObjects数组,我正尝试转换为工作日,例如(星期一,星期二,星期三)。

The Array looks like this when I print it to the console: 当我将其打印到控制台时,Array如下所示:

[2014-12-03 22:16:26 +0000, 2014-12-05 22:16:26 +0000, 2014-12-11 22:16:26 +0000] [2014-12-03 22:16:26 +0000,2014-12-05 22:16:26 +0000,2014-12-11 22:16:26 +0000]

This is my Code: 这是我的代码:

var xAxisDates = [AnyObject]()


func dateformatter() {
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

    let weekDayFormatter = NSDateFormatter()
    weekDayFormatter.dateFormat = "EEE"

    println(xAxisDates)

    for i in xAxisDates{

        let date = formatter.dateFromString(i as String)
        println(weekDayFormatter.stringFromDate(date!))
    }
}

The code crash at : 代码崩溃:

  let date = formatter.dateFromString(i as String) 

I have been trying all day to figure out what I am doing wrong, and read practically every question on NSDateFormatter but to no avail. 我整天都在努力找出我做错了什么,并且几乎在NSDateFormatter上阅读了每个问题,但无济于事。 I am down casting i as String because if I don´t I get error message AnyObject is not convertible to String. 我拒绝将我转换为String,因为如果不这样做,我会收到错误消息AnyObject无法转换为String。 My feeling is that the type do not match up, but I am not sure, and I don´t know how to find out. 我的感觉是类型不匹配,但是我不确定,我也不知道如何找出答案。 I have attached the error message as picture if that helps. 如果有帮助,我已将错误消息附加为图片。 If you can recommend a tutorial or book or something on how to understand what is wrong I would appreciate it, as I am trying to learn. 如果您可以推荐一本教程或一本书或有关如何理解错误的内容,在尝试学习时,我将不胜感激。

Any help would be much appreciated ! 任何帮助将非常感激 !

在此处输入图片说明

extension NSDate {
    var weekdayName: String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "EEEE"
        return formatter.stringFromDate(self)
    }
}

let myArrayOfAnyObjects:[AnyObject] = [NSDate()]

myArrayOfAnyObjects.first!.weekdayName   // "Tuesday"

The xAxisDates array contains NSDate objects, therefore xAxisDates数组包含NSDate对象,因此

let date = formatter.dateFromString(i as String)

does not make any sense, and i as String already crashes because i is an NSDate and not a String . 没有任何意义, i as String已经崩溃,因为iNSDate而不是String

You just need to convert the dates to a string: 您只需要将日期转换为字符串即可:

for i in xAxisDates {
    println(weekDayFormatter.stringFromDate(i as NSDate))
}

or better check if the array elements actually are NSDate objects: 或更好地检查数组元素是否实际上是NSDate对象:

for i in xAxisDates {
    if let date = i as? NSDate {
        println(weekDayFormatter.stringFromDate(date))
    }
}

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

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