ios 如何快速获取当前月份的字符串:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43820798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:06:50  来源:igfitidea点击:

How can i get current month as String in swift:

iosswiftnsdatenscalendar

提问by iron

I need to get may as a current month but i could not do. How can i achieve this.

我需要在当月获得可能,但我做不到。我怎样才能做到这一点。

   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

I have done this but does not worked.

我已经这样做了,但没有用。

回答by André Slotta

let now = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "LLLL"
let nameOfMonth = dateFormatter.string(from: now)

回答by Balaji Galave

If you are using Swift 3.0then extensions and Dateclass are great way to go.

如果您使用的是Swift 3.0,那么扩展和Date类是不错的选择。

try below code

试试下面的代码

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

Get work with it like below:

像下面一样使用它:

 let date = Date()
 let monthString = date.month

回答by Luke Stanyer

You use DateFormatter() see below for this used in an extension to Date.

您使用 DateFormatter() 见下文,用于 Date 的扩展中。

Add this anywhere in your project in global scope.

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

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

}

}

Then you can use this anywhere in your code.

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

let date = Date()
date.monthAsString() // Returns current month e.g. "May"