2016-07-24 103 views
1

我在尝试将fajerTime转换为NSDate。当我编译项目dateValuenil。任何想法如何解决这个问题?如何将字符串转换为NSdate?

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")      
    } 
+0

的可能的复制[如何字符串转换为NSDate的在iphone?(http://stackoverflow.com/questions/6288371/how-to-convert-string-to-nsdate-in-iphone ) –

+0

显示'fajerTime'的内容 – Arsen

+0

问题可能是'fajerTime'的格式。看起来'fajerTime'是一个时间字符串,例如'12:34',而日期格式化器被配置为接受包含月份,日期和年份的字符串,例如, '24-07-2016'。您需要根据“MM-dd-yyyy”格式格式化“fajerTime”,或者配置日期格式化程序以接受一段时间,例如, 'dateFormatter.dateFormat =“hh:mm”'。 –

回答

0

问题似乎是格式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! 
0

请按照例如(斯威夫特3):

let dateStr = "2016-01-15 20:10:01 +0000" 
let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z" 
let myDate = dateFormatter.date(from: dateStr) 

请记住:

  • 日期格式例如“YYYY-MM-DD HH:MM:SS Z” 必须日期字符串模式

  • 在你的情况 格式化只包含日期匹配,你的日期字符串只包含时间,但是,你的约会

  • 当使用dateFormatter.date()就没有必要将其转换为日期,因为它返回一个日期: enter image description here

有用网站的日期格式: