0

I have a date "2017-12-31" as a String.

What I want to get finally is only the month: "12" as a String.

So I thought that I can change it to Date using a date formatter

let formatter = DateFormatter()
formatter.dateFormat = "MM"

What do I do next?

3 Answers 3

3
let dateString = "2017-12-31"    
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)    formatter.timeZone = TimeZone(identifier:  TimeZone.autoupdatingCurrent.identifier)
formatter.dateFormat = "yyyy-MM-dd" 
let localDate = formatter.date(from: dateString) 
formatter.dateFormat = "MM" 
let strMonth = formatter.string(from: localDate!)
print("Month is:",strMonth)

Another way

let dateString = "2017-12-31"
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let localDate = formatter.date(from: dateString)
let month = String(NSCalendar.current.component(.month, from: localDate!))
print(month)
Sign up to request clarification or add additional context in comments.

2 Comments

the current timezone it is used by the default so it is not needed. Btw why not simply formatter.timeZone = .autoupdatingCurrent. And don't force unwrap your date. It would crash the app in case of an invalid date string.
And Swift 3 or later you should drop the NS and use Calendar instead of NSCalendar. Note that for stand alone month it is recommended to use "LL" instead of "MM" i.sstatic.net/lkYVY.png
2

First you have to use the DateFormatter to create a temporary Date object from your source String object. Then you have to use it to create your final String from the temporary Date object.

let dateString = "2017-12-31"
let dateFormatter = DateFormatter()

// set the dateFormatter's dateFormat to the dateString's format
dateFormatter.dateFormat = "yyyy-MM-dd"

// create date object
guard let tempDate = dateFormatter.date(from: dateString) else {
    fatalError("wrong dateFormat")
}

// set the dateFormatter's dateFormat to the output format you wish to receive
dateFormatter.dateFormat = "LL" // LL is the stand-alone month

let month = dateFormatter.string(from: tempDate)

Comments

2

Use below function for getting month from string file of date

func getMonthFromDateString(strDate: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let date = formatter.date(from: strDate) // Convert String File To Date
        formatter.dateFormat = "MM"
        let strMM = formatter.string(from: date!) // Convert date to string
        return strMM
}

1 Comment

I don't think it's working because yourDate is wrong... should be date... ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.