2011-11-17 60 views
9

我想添加天的日期,我得到了很多代碼這一點,但他們都不工作了我下面顯示的是我的代碼,請別人幫我解決這個問題添加天的NSDate

int daysToAdd=[[appDlegateObj.selectedSkuData 
            objectForKey:@"Release Time"] intValue]; 

NSTimeInterval secondsForFollowOn=daysToAdd*24*60*60; 

NSString *dateStr=[contentDic objectForKey:@"Date"]; 

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init]; 

[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 

NSDate *dateFromString=[[NSDate alloc]init]; 

dateFromString=[dateFormatter dateFromString:dateStr]; 

[dateFormatter release]; 

NSDate *date=[dateFromString dateByAddingTimeInterval:secondsForFollowOn]; 

回答

28
// Initialize stringified date presentation 
NSString *myStringDate = @"2011-11-17"; 

// How much day to add 
int addDaysCount = 30; 

// Creating and configuring date formatter instance 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 

// Retrieve NSDate instance from stringified date presentation 
NSDate *dateFromString = [dateFormatter dateFromString:myStringDate]; 

// Create and initialize date component instance 
NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; 
[dateComponents setDay:addDaysCount]; 

// Retrieve date with increased days count 
NSDate *newDate = [[NSCalendar currentCalendar] 
           dateByAddingComponents:dateComponents 
               toDate:dateFromString options:0]; 

NSLog(@"Original date: %@", [dateFormatter stringFromDate:dateFromString]); 
NSLog(@"New date: %@", [dateFormatter stringFromDate:newDate]); 

// Clean up 
[dateComponents release], dateComponents = nil; 
[dateFormatter release], dateFormatter = nil; 

輸出:

Original date: 2011-11-17 
New date: 2011-12-17 
+0

謝謝月光,你的代碼工作正常。 – karthick

+0

@moonlight:關於dateByRemovingComponents呢?如果我需要在目前的日期前1個月取得新的日期,我該怎麼辦? –

+2

@BishalGhimire setMonth爲-1(用於'dateComponents')或任何你想要減去的數字。 –

3

您可以通過添加一個時間間隔

NSDate* newDate = [date dateWithTimeInterval:3600*24*numberOfDays sinceDate:otherDate]; 

但如果你想成爲真正準確瞭解它,並考慮到閏秒,日光節約時間和所有這種東西你可能想加入天一個NSDate按照Date and Time Programming GuideOmtara's link中所述使用NSDateComponents。

2

我建議您查看this文章以獲得更清潔的解決方案。

+1

雖然這可能會在理論上回答這個問題,但我們希望您在回答中包含鏈接文章的基本部分,並提供[鏈接供參考](http://meta.stackexchange.com/q/8259 )。如果做不到這一點,答案就會受到鏈接腐敗的威脅。 – Kev

+0

鏈接頁面中的引用內容非常簡潔。我曾經在iPhone應用程序中擁有相同的需求,並發現這個頁面很有用。 – Omtara

+0

感謝那個參考Omtara。這是完美的。 –

-1
NSDate *Date=[datePicker date]; 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"dd.MM.yy EEEE h:mm a"]; 
+0

這並沒有回答這個問題。 – jbat100

2
NSDateComponents *offsetComponents = [[NSDateComponents alloc] autorelease]; 
[offsetComponents setDay:1]; 

newDate = [[[CalendarContainer sharedCalendarContainer] gregorian] dateByAddingComponents:offsetComponents toDate:currentlyDisplayedDate options:0]; 
8
NSDate *now = [NSDate date]; 
    int daysToAdd = 1; 
    NSDate *newDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd]; 
3

與iOS 8和10.9,現在可以真正做到這一點輕鬆了許多。您可以將任何數量的任何日曆單位添加到日期。我在NSDate上聲明瞭一個非常小的類別方法,使它更快(因爲我只需要在整個應用程序中添加幾天)。下面的代碼。

-(NSDate *)addDaysToDate:(NSNumber *)numOfDaysToAdd { 
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:numOfDaysToAdd.integerValue toDate:self options:nil]; 
    return newDate; 
} 

關鍵的事情:NSCalendarUnitDay是我曾經讓它知道我想添加幾天。您可以將其更改爲其他枚舉值,如月或年。

由於它是NSDate上的一個類別,我將該值添加到自我。如果你不想申報的類別,你只需要一個日期的方法參數,如:

-(NSDate *)addDays:(NSNumber *)numOfDaysToAdd toDate:(NSDate *)originalDate { 
    NSDate *newDate = [[NSCalendar currentCalendar] dateByAddingUnit:NSCalendarUnitDay value:numOfDaysToAdd.integerValue toDate:originalDate options:nil]; 

    return newDate; 
} 

我使用的NSNumber,但你可以很容易地只使用一個NSInteger。

最後,斯威夫特:

func addDaysToDate(daysToAdd: Int, originalDate: NSDate) -> NSDate? { 
     let newDate = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.DayCalendarUnit, value: daysToAdd, toDate: originalDate, options: nil) 
     return newDate 
    } 

如果你想擺脫的NSDate的?並且解開一個可能的零(添加日期可能會失敗)感覺很舒服,你可以直接返回newDate!並擺脫?標記。

1

in Swift 2.1.X and xcode 7.1 OSX 10.10。5,你可以向前添加任意天數和向後使用功能

func addDaystoGivenDate(baseDate:NSDate,NumberOfDaysToAdd:Int)->NSDate 
{ 
    let dateComponents = NSDateComponents() 
    let CurrentCalendar = NSCalendar.currentCalendar() 
    let CalendarOption = NSCalendarOptions() 

    dateComponents.day = NumberOfDaysToAdd 

    let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: baseDate, options: CalendarOption) 
    return newDate! 
} 

函數調用了80天

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80) 
print(newDate) 
9天

遞增當前日期
var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9) 
print(newDate) 

函數調用遞減當前日期

0

在Swift 2中,使用extension來擴展NSDate:

extension NSDate { 

    func addDays(days:Int) -> NSDate{ 
     let newDate = NSCalendar.currentCalendar().dateByAddingUnit(
      .Day, 
      value: days, 
      toDate: self, 
      options: NSCalendarOptions(rawValue: 0)) 

     return newDate! 
    } 
}