gpt4 book ai didi

swift - 如何将字符串转换为 NSdate?

转载 作者:行者123 更新时间:2023-11-28 08:32:45 24 4
gpt4 key购买 nike

我正在尝试将 fajerTime 转换为 NSDate。当我编译项目时,dateValuenil。知道如何解决这个问题吗?

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!

关于swift - 如何将字符串转换为 NSdate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38552429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com