解析Swift字符串到日期,然后解析组件

时间:2017-11-25 09:58:07

标签: swift nsdateformatter foundation date-parsing

我的日期为“2017-12-31”,为<tr> @foreach (var in cell in row.ItemArray) { if (cell ! = null) { <td>@cell.ToString()</td> } else { <td></td> } } <td>@* Render something at the end of the row*@</td> </tr>

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

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

Date

接下来我该怎么做?

3 个答案:

答案 0 :(得分: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)

另一种方式

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)

答案 1 :(得分:2)

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

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)

答案 2 :(得分:2)

使用以下功能从日期的字符串文件中获取月份

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
}