我正在尝试编写一个带字符串的函数(格式为“dd MM yyyy”)并返回给定参数之后的第二天。
例如:
let nextDay = getNextDay("31 12 2016")
print(nextDay)
会打印:
01 01 2017
有人可以告诉我该怎么做吗?感谢
答案 0 :(得分:5)
以下代码段可以为您提供帮助。
//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)")
}
答案 1 :(得分:2)
class DateHelper
{
lazy var formatter:DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "dd MM yyyy"
return formatter
}()
lazy var dateComponents:DateComponents = {
var dateComp = DateComponents()
dateComp.day = 1
return dateComp
}()
func getNext(dateString:String) -> String?
{
if let date = self.formatter.date(from: dateString),
let nextDate = Calendar.current.date(byAdding: self.dateComponents, to: date)
{
return self.formatter.string(from: nextDate)
}
return nil
}
}
DateHelper().getNext(dateString: "31 12 2016")