如何在NSDate中添加1天?

And*_*rew 309 cocoa-touch date objective-c nsdate

基本上,正如标题所说.我想知道我怎么能加1天NSDate.

如果它是:

21st February 2011
Run Code Online (Sandbox Code Playgroud)

它会变成:

22nd February 2011
Run Code Online (Sandbox Code Playgroud)

或者如果是:

31st December 2011
Run Code Online (Sandbox Code Playgroud)

它会变成:

1st January 2012.
Run Code Online (Sandbox Code Playgroud)

Zak*_*man 696

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);
Run Code Online (Sandbox Code Playgroud)

这应该是不言自明的.

  • 比选择的答案更好的解决方案 (58认同)
  • +1使用日期组件而不是添加一天的秒数. (19认同)
  • 您还可以使用负分量从日期中减去. (16认同)
  • 如果您使用Chri的解决方案,您将陷入白天节省时间...... (2认同)
  • 在Swift中,您需要将`dateByAddingComponents`调用的最后一个参数更改为`NSCalendarOptions(rawValue:0)` (2认同)

Ben*_*air 261

从iOS 8开始就可以使用了 NSCalendar.dateByAddingUnit

Swift 1.x中的示例:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
         .CalendarUnitDay, 
         value: 1, 
         toDate: today, 
         options: NSCalendarOptions(0)
    )
Run Code Online (Sandbox Code Playgroud)

Swift 2.0:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
        .Day, 
        value: 1, 
        toDate: today, 
        options: []
    )
Run Code Online (Sandbox Code Playgroud)

Swift 3.0:

let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)
Run Code Online (Sandbox Code Playgroud)

  • 是Swift还是内置`date.add(.days,1)`这样的东西,难道不是我吗?*去建立一个扩展 (4认同)
  • @quemeful`扩展日期{功能添加(_组件:Calendar.Component,_值:整数)->日期?{return Calendar.current.date(byAdding:component,value:value,to:self)}}`用法`Date()。adding(.day,1)//“ 2019年6月6日下午5:35”` (2认同)

iHS*_*iHS 72

试试这个

 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];
Run Code Online (Sandbox Code Playgroud)


Vik*_*ica 34

iOS 8 +,OSX 10.9 +,Objective-C

NSCalendar *cal = [NSCalendar currentCalendar];    
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay 
                                   value:1 
                                  toDate:[NSDate date] 
                                 options:0];
Run Code Online (Sandbox Code Playgroud)


Ben*_*ess 27

一个基于高维护的答案和vikingosegundo评论的Swift 3&4工作实现.此日期扩展还包含更改年,月和时间的其他选项:

extension Date {

    /// Returns a Date with the specified amount of components 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? {
        let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
        return Calendar.current.date(byAdding: components, to: self)
    }

    /// Returns a Date with the specified amount of components 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? {
        return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
    }

}
Run Code Online (Sandbox Code Playgroud)

按OP的要求仅添加一天的用法将是:

let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)
Run Code Online (Sandbox Code Playgroud)

  • 好吧,我实际上意味着不同的东西:https://gist.github.com/vikingosegundo/31ddb14920415ef444a9ab550411d4ff (3认同)
  • 您可以通过使用日期组件来大量缩短代码。 (2认同)

Jos*_*nce 22

Swift 4.0(在这个精彩的答案中与Swift 3.0相同,只是让我这样的新手清楚)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
Run Code Online (Sandbox Code Playgroud)

  • 你忘记更改你的变量名了吗? (3认同)

小智 13

Swift 4 更新:

let now = Date() // the current date/time
let oneDayFromNow = Calendar.current.date(byAdding: .day, value: 1, to: now) // Tomorrow with same time of day as now
Run Code Online (Sandbox Code Playgroud)


Bhu*_*dra 12

使用以下函数并使用days paramater获取日期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;
}
Run Code Online (Sandbox Code Playgroud)


Ste*_* Ng 10

在迅速

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
Run Code Online (Sandbox Code Playgroud)


AmJ*_*mJa 8

Swift 3.0非常简单的实现方式是:

func dateByAddingDays(inDays: Int) -> Date {
    let today = Date()
    return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
Run Code Online (Sandbox Code Playgroud)


Den*_*kov 7

这是工作!

    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];
Run Code Online (Sandbox Code Playgroud)

  • 我的答案更正确,因为如果您使用NSCalendarWrapComponents(0)选项,则只能在当前月份的范围内创建日期.这意味着,如果您将2016年1月31日的NSCalendarWrapComponents添加1天,您将获得2016年1月1日.使用NSCalendarMatchStrictly选项,您将获得下一个日历日期. (2认同)

pka*_*amb 7

昨天和明天的任何日期的简单 Swift 扩展:

extension Date {
    
    var previousDay: Date {
        Calendar.current.date(byAdding: DateComponents(day:-1), to: self)!
    }
    
    var nextDay: Date {
        Calendar.current.date(byAdding: DateComponents(day:+1), to: self)!
    }
    
}
Run Code Online (Sandbox Code Playgroud)

我根据此处问题中的建议强制展开选项:
When does dateByAddingComponents:toDate:options return nil?


Car*_*ine 5

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

NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];
Run Code Online (Sandbox Code Playgroud)

好的 - 我认为这对我有用。但是,如果您使用它向 2013 年 3 月 31 日添加一天,它将返回一个仅添加了 23 小时的日期。实际上很可能有 24,但在计算中仅添加了 23:00 小时。

同样,如果您向前移动到 2013 年 10 月 28 日,则代码会添加 25 小时,导致日期时间为 2013-10-28 01:00:00。

为了添加一天,我在顶部做了事情,添加了:

NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
Run Code Online (Sandbox Code Playgroud)

很复杂,主要是由于夏令时。


Rah*_*pta 5

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];
Run Code Online (Sandbox Code Playgroud)


Dha*_*esh 5

在 Swift 2.1.1 和 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!
}
Run Code Online (Sandbox Code Playgroud)

将当前日期增加 9 天的函数调用

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)
Run Code Online (Sandbox Code Playgroud)

将当前日期减少 80 天的函数调用

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
 print(newDate)
Run Code Online (Sandbox Code Playgroud)


n.b*_*y.n 5

这是一个通用方法,可让您在指定日期中添加/减去任何类型的单位(年/月/日/小时/秒等)。

使用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
Run Code Online (Sandbox Code Playgroud)


que*_*ful 5

迅捷4.0

extension Date {
    func add(_ unit: Calendar.Component, value: Int) -> Date? {
        return Calendar.current.date(byAdding: unit, value: value, to: self)
    }
}
Run Code Online (Sandbox Code Playgroud)

用法

date.add(.day, 3)!   // adds 3 days
date.add(.day, -14)!   // subtracts 14 days
Run Code Online (Sandbox Code Playgroud)

注意:如果您不知道为什么代码行以感叹号结尾,请在Google上查找“ Swift Optionals”。