我的目标是在特定年份添加一年时额外的一天:
游乐场:
var dateFormatter = DateFormatter()
var startDateString = "2015-01-05"
dateFormatter.dateFormat = "yyyy-MM-dd"
var startDate = dateFormatter.date(from: startDateString)
let result = Calendar.current.date(byAdding: .year, value: 1, to: startDate!)
我希望得到Jan 6, 2016, 12:00 AM
好的,我可以在结果中添加更多代码:
let finalResult = Calendar.current.date(byAdding: .day, value: 1, to: result!)
// January 6 etc...
是否有更简单的代码?
答案 0 :(得分:1)
您可以在一次操作中添加任意“日期组件”:
let dateComponents = DateComponents(year: 1, day: 1)
let result = Calendar.current.date(byAdding: dateComponents, to: startDate!)
也可以使用 DateComponents
代替日期格式化程序来创建
在你的情况下约会:
let startDate = DateComponents(calendar: Calendar.current, year: 2015, month: 1, day: 5).date