【问题标题】:iOS Swift - Execute function if current date is equal to number of this monthiOS Swift - 如果当前日期等于本月数,则执行函数
【发布时间】:2017-05-10 21:01:05
【问题描述】:

我有一个包含默认 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!")
}

谢谢!

【问题讨论】:

    标签: ios swift string date formatting


    【解决方案1】:

    这就是你获得月份的方式

    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!)
    

    【讨论】:

      【解决方案2】:
      let date = Date()
      let calendar = Calendar.current
      
      let StringsMonth = 5 
      let CurrentMonth = calendar.component(.month, from: date)
      
      if StringsMonth == CurrentMonth {
         print("WORKS!")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-28
        • 2018-08-05
        相关资源
        最近更新 更多