我如何在swift中获得String当前月份:

iro*_*ron 27 nsdate nscalendar ios swift

我需要得到可能作为当月,但我做不到.我怎样才能做到这一点.

   let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([.Day , .Month , .Year], fromDate: date)

    let year =  components.year
    let month = components.month
    let day = components.day
Run Code Online (Sandbox Code Playgroud)

我做了这个,但没有奏效.

And*_*tta 68

let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)
Run Code Online (Sandbox Code Playgroud)

  • 单独月份的正确格式是LLLL http://userguide.icu-project.org/formatparse/datetime (4认同)
  • @codddeer123默认情况下,`DateFormatter`使用设备的语言环境.您可以通过设置不同的语言环境来覆盖它:`dateFormatter.locale = Locale(identifier:"es")` (3认同)

Bal*_*ave 29

如果您使用的是Swift 3.0,那么扩展和Date类是很好的方法.

尝试以下代码

extension Date {
    var month: String {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "MMMM"
        return dateFormatter.string(from: self)
    }    
}
Run Code Online (Sandbox Code Playgroud)

像下面这样使用它:

 let date = Date()
 let monthString = date.month
Run Code Online (Sandbox Code Playgroud)


Luk*_*yer 5

您可以在下面的Date扩展中使用DateFormatter()进行此操作。

将其添加到项目中全局范围内的任何位置。

extension Date {
    func monthAsString() -> String {
            let df = DateFormatter()
            df.setLocalizedDateFormatFromTemplate("MMM")
            return df.string(from: self)
    }
Run Code Online (Sandbox Code Playgroud)

}

然后,您可以在代码中的任何地方使用它。

let date = Date()
date.monthAsString() // Returns current month e.g. "May"
Run Code Online (Sandbox Code Playgroud)