iphone - swift time class




NSDate에 하루를 어떻게 추가합니까? (16)

기본적으로 제목에 나와 있습니다. NSDate 하루를 어떻게 추가 할 수 있을지 궁금합니다.

그래서 그것은 :

21st February 2011

그것은 될 것이다 :

22nd February 2011

또는 다음과 같은 경우 :

31st December 2011

그것은 될 것이다 :

1st January 2012.

Andy의 답변에 기반한 Swift 3 & 4 구현 및 년, 월, 시간을 변경할 수있는 추가 옵션이있는 Date 확장 기능 :

extension Date {

    /// Returns a Date with the specified days added to the one it is called with
    func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date {
        var targetDay: Date
        targetDay = Calendar.current.date(byAdding: .year, value: years, to: self)!
        targetDay = Calendar.current.date(byAdding: .month, value: months, to: targetDay)!
        targetDay = Calendar.current.date(byAdding: .day, value: days, to: targetDay)!
        targetDay = Calendar.current.date(byAdding: .hour, value: hours, to: targetDay)!
        targetDay = Calendar.current.date(byAdding: .minute, value: minutes, to: targetDay)!
        targetDay = Calendar.current.date(byAdding: .second, value: seconds, to: targetDay)!
        return targetDay
    }

    /// Returns a Date with the specified days subtracted from the one it is called with
    func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date {
        let inverseYears = -1 * years
        let inverseMonths = -1 * months
        let inverseDays = -1 * days
        let inverseHours = -1 * hours
        let inverseMinutes = -1 * minutes
        let inverseSeconds = -1 * seconds
        return add(years: inverseYears, months: inverseMonths, days: inverseDays, hours: inverseHours, minutes: inverseMinutes, seconds: inverseSeconds)
    }

}

OP가 요청한대로 하루를 추가하는 용도는 다음과 같습니다.

let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)

의 제안에 기반한 대체 솔루션 :

extension Date {

    /// Returns a Date with the specified amount of calendar components added to the one it is called with
    func add(_ components: [Calendar.Component: Int]) -> Date {
        var targetDate = self
        components.forEach { targetDate = Calendar.current.date(byAdding: $0.key, value: $0.value, to: self)! }
        return targetDate
    }

    /// Returns a Date with the specified amount of calendar components subtracted from the one it is called with
    func subtract(_ components: [Calendar.Component: Int]) -> Date {
        var negativeComponents = [Calendar.Component: Int]()
        components.forEach { negativeComponents[$0.key] = -1 * $0.value }
        return add(negativeComponents)
    }

}

조정 된 사용법 :

let today = Date() // date is then today for this example
let tomorrow = today.add([.day: 1])

NSDate의 메서드를 사용할 수 있습니다 - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds 여기서 seconds60 * 60 * 24 = 86400


Swift 3.0 매우 간단한 구현은 다음과 같습니다.

func dateByAddingDays(inDays:NSInteger)->Date{
    let today = Date()
    return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}

iOS 8 이상, OSX 10.9 이상, Objective-C

NSCalendar *cal = [NSCalendar currentCalendar];    
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay 
                                   value:1 
                                  toDate:[NSDate date] 
                                 options:0];

그것은 작동합니다!

    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit unit = NSCalendarUnitDay;
    NSInteger value = 1;
    NSDate *today = [NSDate date];
    NSDate *tomorrow = [calendar dateByAddingUnit:unit value:value toDate:today options:NSCalendarMatchStrictly];

나는 똑같은 문제가 있었다. NSDate 확장을 사용하십시오.

- (id)dateByAddingYears:(NSUInteger)years
                 months:(NSUInteger)months
                   days:(NSUInteger)days
                  hours:(NSUInteger)hours
                minutes:(NSUInteger)minutes
                seconds:(NSUInteger)seconds
{
    NSDateComponents * delta = [[[NSDateComponents alloc] init] autorelease];
    NSCalendar * gregorian = [[[NSCalendar alloc]
                               initWithCalendarIdentifier:NSCalendarIdentifierGregorian] autorelease];

    [delta setYear:years];
    [delta setMonth:months];
    [delta setDay:days];
    [delta setHour:hours];
    [delta setMinute:minutes];
    [delta setSecond:seconds];

    return [gregorian dateByAddingComponents:delta toDate:self options:0];
}

다음은 지정된 날짜에 모든 유형의 단위 (년 / 월 / 일 / 시간 / 초 등)를 더하거나 뺄 수있는 일반적인 목적의 방법입니다.

Swift 2.2 사용

func addUnitToDate(unitType: NSCalendarUnit, number: Int, date:NSDate) -> NSDate {

    return NSCalendar.currentCalendar().dateByAddingUnit(
        unitType,
        value: number,
        toDate: date,
        options: NSCalendarOptions(rawValue: 0))!

}

print( addUnitToDate(.Day, number: 1, date: NSDate()) ) // Adds 1 Day To Current Date
print( addUnitToDate(.Hour, number: 1, date: NSDate()) ) // Adds 1 Hour To Current Date
print( addUnitToDate(.Minute, number: 1, date: NSDate()) ) // Adds 1 Minute To Current Date

// NOTE: You can use negative values to get backward values too

스위프트 2.0

let today = NSDate()    
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)

신속하게 NSDate에서 메소드를 추가하도록 확장 할 수 있습니다.

extension NSDate {
    func addNoOfDays(noOfDays:Int) -> NSDate! {
        let cal:NSCalendar = NSCalendar.currentCalendar()
        cal.timeZone = NSTimeZone(abbreviation: "UTC")!
        let comps:NSDateComponents = NSDateComponents()
        comps.day = noOfDays
        return cal.dateByAddingComponents(comps, toDate: self, options: nil)
    }
}

당신은 이것을 다음과 같이 사용할 수 있습니다.

NSDate().addNoOfDays(3)

신속한 2.2 :

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day,
        value: 1,
        toDate: today,
        options: NSCalendarOptions.MatchStrictly)

희망이 사람을 돕는다!


아래 함수를 사용하고 요일 매개 변수를 사용하여 요일 daysAhead / daysBehind 매개 변수를 미래 날짜에 대해 양수 또는 이전 날짜에 대한 음수로 전달하십시오.

+ (NSDate *) getDate:(NSDate *)fromDate daysAhead:(NSUInteger)days
{
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    dateComponents.day = days;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *previousDate = [calendar dateByAddingComponents:dateComponents
                                                     toDate:fromDate
                                                    options:0];
    [dateComponents release];
    return previousDate;
}

이 시도

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
 // now build a NSDate object for the next day
 NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
 [offsetComponents setDay:1];
 NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate: [NSDate date] options:0];
 [offsetComponents release];
 [gregorian release];

스위프트 4.0 (스위프트 3.0과 똑같은 훌륭한 답변으로 나와 같은 신인들에게 분명히 알립니다)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: now)

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);

NSDate *today=[NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents *components=[[NSDateComponents alloc] init];
components.day=1;
NSDate *targetDate =[calendar dateByAddingComponents:components toDate:today options: 0];

NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
dayComponent.day = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar dateByAddingComponents:dayComponent toDate:[NSDate date] options:0];

NSLog(@"nextDate: %@ ...", nextDate);

이것은 자명하다.





nsdate