从当前日期减去7天

时间:2012-04-18 12:32:09

标签: objective-c ios nsdate

似乎我不能从当前日期减去7天。这就是我的做法:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-7];
NSDate *sevenDaysAgo = [gregorian dateByAddingComponents:offsetComponents toDate:[NSDate date] options:0];

SevenDaysAgo获得与当前日期相同的价值。

请帮忙。

编辑:在我的代码中,我忘了用正确的日期替换获取当前日期的变量。所以上面的代码是有用的。

11 个答案:

答案 0 :(得分:185)

的代码:

NSDate *currentDate = [NSDate date];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setDay:-7];
NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"\ncurrentDate: %@\nseven days ago: %@", currentDate, sevenDaysAgo);
[dateComponents release];

输出:

currentDate: 2012-04-22 12:53:45 +0000
seven days ago: 2012-04-15 12:53:45 +0000

我完全同意JeremyP。

BR。
尤金

答案 1 :(得分:114)

如果你至少运行iOS 8或OS X 10.9,那就更简洁了:

NSDate *sevenDaysAgo = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay
                                                                value:-7
                                                               toDate:[NSDate date]
                                                              options:0];

或者,使用Swift 2:

let sevenDaysAgo = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -7,
    toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))

随着Swift 3及以上,它变得更加紧凑:

let sevenDaysAgo = Calendar.current.date(byAdding: .day, value: -7, to: Date())

答案 2 :(得分:107)

使用dateByAddingTimeInterval方法:

NSDate *now = [NSDate date];
NSDate *sevenDaysAgo = [now dateByAddingTimeInterval:-7*24*60*60];
NSLog(@"7 days ago: %@", sevenDaysAgo);

输出:

7 days ago: 2012-04-11 11:35:38 +0000

希望有所帮助

答案 3 :(得分:37)

Swift 3

Calendar.current.date(byAdding: .day, value: -7, to: Date())

答案 4 :(得分:4)

dymv的回答非常好。这可以在swift中使用

# find the ruby environment (one time only)
rvm env --path -- ruby-version[@gemset-name]

# set the source returned, e.g.
source /usr/local/rvm/environments/ruby-2.1.1@projectX
ruby -v

你可以用

来调用它
extension NSDate {    
    static func changeDaysBy(days : Int) -> NSDate {
        let currentDate = NSDate()
        let dateComponents = NSDateComponents()
        dateComponents.day = days
        return NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: currentDate, options: NSCalendarOptions(rawValue: 0))!
    }
}

希望它对dymv有所帮助,并希望对此有所帮助

答案 5 :(得分:3)

Swift 4.2 iOS 11.x Babec's解决方案,纯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)!
  }
}

答案 6 :(得分:2)

Swift 4.2-变异(更新)自我

这是原始海报在一周前获得日期变量(本身具有更新/突变)的另一种方式。

extension Date {
    mutating func changeDays(by days: Int) {
        self = Calendar.current.date(byAdding: .day, value: days, to: self)!
    }
}

用法

var myDate = Date()       // Jan 08, 2019
myDate.changeDays(by: 7)  // Jan 15, 2019
myDate.changeDays(by: 7)  // Jan 22, 2019
myDate.changeDays(by: -1) // Jan 21, 2019

// Iterate through one week
for i in 1...7 {
    myDate.changeDays(by: i)
    // Do something
}

答案 7 :(得分:1)

使用运算符扩展名:

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

答案 8 :(得分:0)

原始接受的答案的Swift 3.0+版本

Date()。addingTimeInterval(-7 * 24 * 60 * 60)

但是,这仅使用绝对值。在大多数情况下,使用日历答案可能更合适。

答案 9 :(得分:-2)

FOR SWIFT 3.0

这里是功能,您可以减少任何计数的天,月,日 比如这里,我把当前的系统日期减少了100年,你可以做到白天,月也 只需设置柜台 并将它存储在一个数组中,你可以随时随地使用这个数组 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)
        }

答案 10 :(得分:-2)

斯威夫特3:

对Dov的回答的修改。

extension Date {

    func dateBeforeOrAfterFromToday(numberOfDays :Int?) -> Date {

        let resultDate = Calendar.current.date(byAdding: .day, value: numberOfDays!, to: Date())!
        return resultDate
    }
}

用法:

let dateBefore =  Date().dateBeforeOrAfterFromToday(numberOfDays : -7)
let dateAfter = Date().dateBeforeOrAfterFromToday(numberOfDays : 7)
print ("dateBefore : \(dateBefore), dateAfter :\(dateAfter)")