我正试图将fajerTime转换为NSDate。当我编译这个项目时,dateValue就是nil。知道怎么解决这个问题吗?

if prayerCommingFromAdan.id == 0 && prayerCommingFromAdan.ringToneId != 0{
    //   NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)

    let fajerTime = "\(prayer0.time[0...1]):\(prayer0.time[3...4])" as String
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"
    dateFormatter.timeZone = NSTimeZone.localTimeZone()

    // convert string into date
    let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!
    print(dateValue)

    var dateComparisionResult:NSComparisonResult = NSDate().compare(dateValue)

    if dateComparisionResult == NSComparisonResult.OrderedDescending {
        addNotificationAlarm(year, month: month, day: day, hour: prayer0.time[0...1], minutes: prayer0.time[3...4], soundId: prayerCommingFromAdan.ringToneId, notificationBody: "It is al fajr adan")
    }

最佳答案

问题似乎是fajerTime的格式。看起来fajerTime是一个时间字符串,例如12:34,而日期格式化程序被配置为接受包含月、日和年的字符串,例如24-07-2016
您需要格式化fajerTime以包含年、月和日以及时间。还要配置日期格式化程序以接受完整的日期和时间。
假设prayer0是一个数组,您还需要使用joinWithSeparator将元素组合成一个字符串。
例如

let hours = prayer0.time[0...1].joinWithSeparator("")
let minutes = prayer0.time[3...4].joinWithSeparator("")
let fajerTime = "\(month)-\(day)-\(year) \(hours):\(minutes)"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy hh:mm"
dateFormatter.timeZone = NSTimeZone.localTimeZone()

// convert string into date
let dateValue = dateFormatter.dateFromString(fajerTime) as NSDate!

09-17 19:57