How can I get the current month as String?

63,962

Solution 1

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

Solution 2

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

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"
Share:
63,962
iron
Author by

iron

Updated on July 31, 2022

Comments

  • iron
    iron almost 2 years

    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.

  • iron
    iron about 7 years
    should i use NSdate date is undeclared ....swift 2
  • iron
    iron about 7 years
    i am using swift 2
  • Leo Dabus
    Leo Dabus about 7 years
    The correct format for stand alone month is LLLL userguide.icu-project.org/formatparse/datetime
  • Balaji Galave
    Balaji Galave about 7 years
    just get on Swift 3.0 if you can bro. bcz its a lot happening on latest swift
  • mikro098
    mikro098 about 6 years
    Is it possible to set the language of the returned month? I tried using locale but it doesn't work. I want to get the current language that is set on iPhone
  • André Slotta
    André Slotta almost 6 years
    @codddeer123 The DateFormatter uses the device's locale by default. You can override it by setting a different locale of course: dateFormatter.locale = Locale(identifier: "es")
  • cspam
    cspam about 5 years
    Swift 4.0 Solution: DateFormatter().monthSymbols[currentMonth - 1]
  • craft
    craft about 2 years
    If you are displaying something more than just the month, for example month and day, this might be prone to issues. Better to use .setLocalizedDateFormatFromTemplate to account for possible localization format order differences.