Search code examples
swiftnsdateformatterfoundationdate-parsing

Parsing a Swift String to Date, then Components


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?


Solution

  • 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)