我正在尝试编写一个函数,它接受一个字符串(格式为“dd MM yyyy”)并返回作为参数给出的日期之后的日期。
例如:
let nextDay = getNextDay("31 12 2016")
print(nextDay)
将打印:
01 01 2017
谁能告诉我怎么做?谢谢
最佳答案
下面是可能对您有所帮助的代码片段。
//Call method like this
convertNextDate(dateString: "31 12 2016")
// Method is here
func convertNextDate(dateString : String){
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd MM yyyy"
let myDate = dateFormatter.date(from: dateString)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
let somedateString = dateFormatter.string(from: tomorrow!)
print("your next Date is \(somedateString)")
}
另一种方法是创建扩展,这就是它。
extension String {
func convertToNextDate(dateFormat: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = dateFormat
let myDate = dateFormatter.date(from: self)!
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: myDate)
return dateFormatter.string(from: tomorrow!)
}
}
用法
print("31 12 2016".convertToNextDate(dateFormat: "dd MM yyyy"))
注意:您可以使用所需的日期格式,只要确保它是合适的即可。
关于ios - Swift - 获取下一个日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490848/