2011-11-17 108 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! 
    } 
}