program story

현재 날짜에서 7 일 빼기

inputbox 2020. 8. 10. 08:03
반응형

현재 날짜에서 7 일 빼기


현재 날짜에서 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는 현재 날짜와 동일한 값을 가져옵니다.

도와주세요.

편집 : 내 코드에서 현재 날짜를 올바른 변수로 바꾸는 것을 잊었습니다. 따라서 위의 코드는 작동합니다.


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

도움이되기를 바랍니다.


암호:

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.
유진


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())

스위프트 3

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

dymv의 답변은 훌륭합니다. 이것은 신속하게 사용할 수 있습니다.

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에 도움이되기를 바랍니다.


Swift 4.2-Mutate (업데이트) Self

Here is another way the original poster can get one week ago if he already has a date variable (updates/mutates itself).

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

Usage

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

or

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

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

Swift 3.0+ version of the original accepted answer

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

However, this uses absolute values only. Use calendar answers is probably more suitable in most cases.


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

Swift 3:

A modification to Dov's answer.

extension Date {

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

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

Usage:

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

참고URL : https://stackoverflow.com/questions/10209427/subtract-7-days-from-current-date

반응형