我有这样的日期格式字符串“2015-03-09”。如何从当前日期开始接下来的10天?任何帮助将不胜感激。谢谢提前
答案 0 :(得分:18)
对于纯粹的Swift 3解决方案:
Calendar.current.date(byAdding: .day, value: 10, to: Date())
答案 1 :(得分:16)
以下是如何使用内置日期修改方法10天后获取日期.dateByAddingUnit 如果需要所有10天(日期),可以通过“value:10”部分循环并添加到数组中。
var tenDaysfromNow: NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: 10, toDate: NSDate(), options: [])!
}
print(tenDaysfromNow)
对于Swift3:
var tenDaysfromNow: Date {
return (Calendar.current as NSCalendar).date(byAdding: .day, value: 10, to: Date(), options: [])!
}
答案 2 :(得分:6)
您可以使用dateByAddingTimeInterval()方法。
var dateStr = "2015-03-09"
var formatter = NSDateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var currDate = formatter.dateFromString(dateStr)
for i in 1...10
{
var interval = NSTimeInterval(60 * 60 * 24 * i)
var newDate = currDate?.dateByAddingTimeInterval(interval)
println(newDate)
}
修改强>
正如@Martin R在评论中所提到的,使用NSCalendar类的dateByAddingComponents()会更好:
var calendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)
var dateComponent = NSDateComponents()
for i in 1...10
{
dateComponent.day = i
var newDate = calendar?.dateByAddingComponents(dateComponent, toDate: currDate!, options:nil)
println(newDate)
}
答案 3 :(得分:3)
有一个函数" dateByAddingTimeInterval()'对于NSDate对象。有了这个,您可以从日期字符串创建NSDate。然后添加10天= 10 * 24 * 60 * 60以获得接下来的10天NSDate值
let today : NSDate = ....
let next10days = today.dateByAddingTimeInterval(10*60*60*24); //interval = seconds
//then you convert back to your date string format if you want, by using NSDateFormatter
为避免夏令时保存问题(@MartinR):
let cal = NSCalendar(calendarIdentifier: NSGregorianCalendar)
let next10Days = cal.dateByAddingUnit(NSCalendarUnit.DayCalendarUnit, value: 10, toDate: today, options: nil)
答案 4 :(得分:0)
这里是@MidhunMP的快速4/5版本答案
var dateStr = "2015-03-09"
var formatter = DateFormatter()
formatter.dateFormat = "YYYY-MM-dd"
var calendar = Calendar(identifier: .gregorian)
var dateComponent = DateComponents()
if let currDate = formatter.date(from: dateStr) {
for i in 1...10 {
let newDate = calendar.date(byAdding: .day, value: i, to: currDate)
print(newDate)
}
}