如何在swift 2中将每个日期组件转换为特定的日期格式

时间:2017-08-15 07:08:35

标签: ios swift nsdateformatter

我可以获得各个日期组件:

let dateString = String(dataModel.dateCompletedDay) + String(dataModel.dateCompletedMonth) + String(dataModel.dateCompletedYear)
print(dateString)
//2532016

现在我该如何将其转换为DD / MM / YYYY格式?

1 个答案:

答案 0 :(得分:5)

我建议使用DateComponentsDateFormatterlet components = DateComponents(year:dataModel.dateCompletedYear, month: dataModel.dateCompletedMonth, day: dataModel.dateCompletedDay) let calendar = Calendar(identifier: .gregorian)! let date = calendar.date(from: components)! let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy" let dateString = formatter.string(from: date) (Swift 3)

let dateString = String(format: "%02ld/%02ld/%ld", dataModel.dateCompletedDay, dataModel.dateCompletedMonth, dataModel.dateCompletedYear)

此外,这是一个简单的解决方案,应该也适用于Swift 2

lapply