我有一个包含默认 Date() 的字符串,它看起来像这样:
"2017-05-10 20:34:18 +0000"
如果这个月的数字与字符串相同,如何运行一个函数? (在这种情况下,月份的数字应该是5)
我认为它可能看起来像这样:
let CurrentMonth = 5 // This number should be the number of the current month
let StringsMonth = 5 // This number should be grabbed from the string shown above.
if StringsMonth == CurrentMonth {
print("WORKS!")
}
谢谢!
最佳答案
这就是你得到月份的方式
let date = Date()
let calendar = Calendar.current
let month = calendar.component(.month, from: date)
这就是你如何转换你的时间戳并得到月份
let datestring = "2017-05-10 20:34:18 +0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZZZ"
let date2 = dateFormatter.date(from: datestring)
let month2 = calendar.component(.month, from: date2!)
关于iOS Swift - 如果当前日期等于本月的数字,则执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43902673/