将 Swift 字符串解析为日期,然后是组件

Parsing a Swift String to Date, then Components

我有一个日期“2017-12-31”作为 String

我最终想要得到的只是月份:“12”作为一个字符串。

所以我认为我可以使用日期格式化程序将其更改为 Date

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

接下来我该做什么?

首先,您必须使用 DateFormatter 从源 String 对象创建临时 Date 对象。然后您必须使用它从临时 Date 对象创建最终的 String

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)

使用下面的函数从日期

的字符串文件中获取月份
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
}
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)

另一种方式

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)