iron
iron

Reputation: 765

How can I get the current month as String?

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.

Upvotes: 61

Views: 76410

Answers (3)

Luke Stanyer
Luke Stanyer

Reputation: 1484

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 monthName() -> 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.monthName() // Returns current month e.g. "May"

Upvotes: 17

Balaji Galave
Balaji Galave

Reputation: 1076

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

Upvotes: 49

André Slotta
André Slotta

Reputation: 14030

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

Upvotes: 118

Related Questions