iOS Swift - 如果当前日期等于本月的数字,则执行函数

标签 ios swift string date formatting

我有一个包含默认 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/

相关文章:

iOS - 工具栏不显示

ios - Dirac 3 LE 库中的方法总是返回 0

ios - 不打印 indexPath.row 处的所有索引

java - 确定字符出现的最大次数并返回起始索引

ios - 如何验证应用程序内购买的 iTunes Store 收据

swift - 如何在 Swift playground 中查看异常?

swift - 如何在运行时更改 Safari 应用程序扩展中的工具栏图标?

swift - 如何在 swift 3 中使用 imageview 嵌套标签

java.lang.NumberFormatException : For input string: "23 " 异常

c# - 在 C# 中验证输入字段