It seems that I can\'t subtract 7 days from the current date. This is how i am doing it:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:N
If you're running at least iOS 8 or OS X 10.9, there's an even cleaner way:
NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay
value:-7
toDate:[NSDate date]
options:0];
Or, with Swift 2:
let sevenDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -7,
toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
And with Swift 3 and up it gets even more compact:
let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())
Calendar.current.date(byAdding: .day, value: -7, to: Date())
FOR SWIFT 3.0
here is fucntion , you can reduce days , month ,day by any count like for example here , i have reduced the current system date's year by 100 year , you can do it for day , month also just set the counter and store it in an array , you can this array anywhere then func currentTime()
{
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let pastyear = year - 100
var someInts = [Int]()
printLog(msg: "\(day):\(month):\(year)" )
for _ in pastyear...year {
year -= 1
print("\(year) ")
someInts.append(year)
}
print(someInts)
}
extension Date {
static func -(lhs: Date, rhs: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: -rhs, to: lhs)!
}
}
let today = Date()
let yesterday = today - 7
Swift 4.2 iOS 11.x Babec's solution, pure Swift
extension Date {
static func changeDaysBy(days : Int) -> Date {
let currentDate = Date()
var dateComponents = DateComponents()
dateComponents.day = days
return Calendar.current.date(byAdding: dateComponents, to: currentDate)!
}
}