How can I get the current month as String?

IosSwiftDateNsdateNscalendar

Ios Problem Overview


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.

Ios Solutions


Solution 1 - Ios

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

Solution 2 - Ios

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

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

Solution 3 - Ios

Swift 3.0 and higher

You use DateFormatter() see below for this used in an extension to 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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionironView Question on Stackoverflow
Solution 1 - IosAndré SlottaView Answer on Stackoverflow
Solution 2 - IosBalaji GalaveView Answer on Stackoverflow
Solution 3 - IosLuke StanyerView Answer on Stackoverflow