131

看来我不能从当前日期减去 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 获得与当前日期相同的值。

请帮忙。

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

4

12 回答 12

199

代码:

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。
尤金

于 2012-04-22T12:56:55.423 回答
144

如果您至少运行 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())
于 2015-02-17T18:26:18.177 回答
115

使用 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

希望能帮助到你

于 2012-04-18T12:36:23.877 回答
64

斯威夫特 3

Calendar.current.date(byAdding: .day, value: -7, to: Date())
于 2016-09-28T16:23:58.887 回答
9

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
}
于 2019-01-09T05:34:31.143 回答
9

Swift 运算符扩展:

extension Date {
    
    static func -(lhs: Date, rhs: Int) -> Date {
        return Calendar.current.date(byAdding: .day, value: -rhs, to: lhs)!
    }
}

用法

let today = Date()
let sevenDayAgo = today - 7
于 2019-11-30T19:53:20.353 回答
5

dymv 的回答很好。这你可以在 swift 中使用

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))!
    }
}

你可以用

NSDate.changeDaysBy(-7) // Date week earlier
NSDate.changeDaysBy(14) // Date in next two weeks

希望对 dymv 有所帮助并感谢

于 2015-09-23T20:13:25.467 回答
4

Swift 4.2 iOS 11.x Babec的解决方案,纯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)!
  }
}
于 2018-10-01T13:21:19.470 回答
3

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

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

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

于 2018-06-25T15:59:55.537 回答
-1

斯威夫特 5

从当前日期添加或减去日期的函数。

func addOrSubtructDay(day:Int)->Date{
  return Calendar.current.date(byAdding: .day, value: day, to: Date())!
}

现在调用函数

var dayAddedDate = addOrSubtructDay(7)
var daySubtractedDate = addOrSubtructDay(-7)
  • 添加日期传递预期日期值
  • 减去传递负日值
于 2021-11-25T05:46:52.623 回答
-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)")
于 2017-07-27T09:19:56.920 回答
-3

斯威夫特 3.0

这是功能,您可以减少天、月、日,例如这里,我已将当前系统日期的年份减少了 100 年,您可以对天、月执行此操作,也只需设置计数器并将其存储在array ,你可以在任何地方使用这个数组然后 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)
        }
于 2017-01-03T15:21:42.207 回答