如何将1天添加到NSDate中?


320

基本上如标题所述。我想知道如何将1天添加到NSDate

因此,如果是:

21st February 2011

它将变成:

22nd February 2011

或如果是:

31st December 2011

它将变成:

1st January 2012.

4
请注意,NSDate不代表日期,而是代表时间点。因此,它包括时间和日期。
罗格

4
同意-您应该在下面使用Zack German的答案。请参阅Apple的日期和时间编程指南
Ash Furrow

向下滚动以获取更新(或更短)的解决方案!
catanore

Answers:


711

Swift 5.0:

var dayComponent    = DateComponents()
dayComponent.day    = 1 // For removing one day (yesterday): -1
let theCalendar     = Calendar.current
let nextDate        = theCalendar.date(byAdding: dayComponent, to: Date())
print("nextDate : \(nextDate)")

目标C:

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

这应该是不言自明的。


19
您还可以使用负分量从日期中减去。
DataGraham

58
比所选答案好得多的解决方案
贾斯汀·迈纳斯

19
+1用于使用日期组件,而不是增加一天的时间。
阿比森

是的,可以很好地节省日光。DST检查的提示:在Mac上重置日期和时间,然后重新启动模拟器,然后它将遵循您的系统时间。
罗伯范登伯格

2
在Swift中,您需要将dateByAddingComponents 通话的最后一个参数更改为NSCalendarOptions(rawValue: 0)
gfpacheco

270

从iOS 8开始,您可以使用 NSCalendar.dateByAddingUnit

Swift 1.x中的示例:

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

Swift 2.0:

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

Swift 3.0:

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

5
是Swift还是内置这样的东西,难道就是我date.add(.days, 1)吗?*进行并建立扩展程序
-quequeful

2
@quemeful extension Date { func adding(_ component: Calendar.Component, _ value: Int) -> Date? { return Calendar.current.date(byAdding: component, value: value, to: self) } }用法Date().adding(.day, 1) // "Jun 6, 2019 at 5:35 PM"
Leo Dabus

82

已为Swift 5更新

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

目标C

 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];

34

iOS 8以上版本,OSX 10.9以上版本,Objective-C

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

请注意,您不能在此处掩盖该设备(只能使用一个)。
catanore

31

一个基于highmaintenance的答案和vikingosegundo的评论的有效Swift 3+实现。此日期扩展名还具有更改年,月和时间的其他选项:

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

}

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

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

2
您可以使用日期组件来大幅缩短代码。
vikingosegundo

您是对的,尽管我认为这样做有缺点:-使用扩展名的代码看起来并不干净-它打开了一些不必要的组件选项,这些组件意义不大,就像let foo = Date().add([.calendar: 1, .yearForWeekOfYear: 3] 我在答案中添加替代解决方案一样。感谢您的建议,@ vikingosegundo!
Benno Kress



13

使用以下函数并使用days参数获取日期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;
}

10

迅速

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)

8

这是工作!

    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];

好吧,显然这个问题是代码转储的天堂。因此,没有理由单挑您。
提请

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

8

Swift 3.0非常简单的实现是:

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

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];

5

迅捷4.0

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

用法

date.add(.day, 3)!   // adds 3 days
date.add(.day, -14)!   // subtracts 14 days

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


3

您可以使用的NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds,其中seconds60 * 60 * 24 = 86400


3
NSDate的addByTimeInterval在iOS 4(bit.ly/vtOzvU)中已弃用。请改用dateByAddingTimeInterval(bit.ly/vRkFrN)。
billmaya 2011年

4
由于夏令时,每天最多可以有23、24或25小时。
vikingosegundo

3

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

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

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)

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

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

3

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

使用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

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

NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];

好的-我认为这对我有用。但是,如果您使用它在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];

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


每天一次只有23个小时。一次25.并且每隔几年就会60*60*24 + 1由于leap秒而变长。日期必须涵盖所有这一切,因此可可的日期处理实际上很棒!
vikingosegundo 2015年

2
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *tomorrowDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE, dd MMM yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:tomorrowDate]);

2

您可以迅速扩展以在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

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

1

对于快速2.2:

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

希望这对某人有帮助!


1

Swift 4,如果您真正需要的只是24小时轮班(60 * 60 * 24秒),而不是“ 1个日历日”

未来: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))

过去: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))


1

迅速更新5

let nextDate = fromDate.addingTimeInterval(60*60*24)

0
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);

0

我有同样的问题; 对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];
}

0

雨燕2.0

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

0

在swift 4或swift 5中,您可以像下面这样使用:

    let date = Date()
    let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: date)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    let yesterday_date = dateFormatter.string(from: yesterday!)
    print("yesterday->",yesterday_date)

输出:

Current date: 2020-03-02
yesterday date: 2020-03-01

0

字符串扩展:转换String_Date>日期

extension String{
  func DateConvert(oldFormat:String)->Date{ // format example: yyyy-MM-dd HH:mm:ss 
    let isoDate = self
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = oldFormat
    return dateFormatter.date(from:isoDate)!
  }
}

扩展名:转换日期>字符串

extension Date{
 func DateConvert(_ newFormat:String)-> String{
    let formatter = DateFormatter()
    formatter.dateFormat = newFormat
    return formatter.string(from: self)
 }
}

扩展名: 获取+/-日期

extension String{
  func next(day:Int)->Date{
    var dayComponent    = DateComponents()
    dayComponent.day    = day
    let theCalendar     = Calendar.current
    let nextDate        = theCalendar.date(byAdding: dayComponent, to: Date())
    return nextDate!
  }

 func past(day:Int)->Date{
    var pastCount = day
    if(pastCount>0){
        pastCount = day * -1
    }
    var dayComponent    = DateComponents()
    dayComponent.day    = pastCount
    let theCalendar     = Calendar.current
    let nextDate        = theCalendar.date(byAdding: dayComponent, to: Date())
    return nextDate!
 }
}

用法:

let today = Date()
let todayString = "2020-02-02 23:00:00"
let newDate = today.DateConvert("yyyy-MM-dd HH:mm:ss") //2020-02-02 23:00:00
let newToday = todayString.DateConvert(oldFormat: "yyyy-MM-dd HH:mm:ss")//2020-02-02
let newDatePlus = today.next(day: 1)//2020-02-03 23:00:00
let newDateMinus = today.past(day: 1)//2020-02-01 23:00:00

参考:来自多个问题
如何将1天添加到NSDate中?
数学函数将正整数转换为负数并将负整数转换为正数?
将NSString转换为NSDate(然后再次返回)


-1

使用以下代码:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

addTimeInterval

现在已弃用。


3
由于夏令时,一天可能有23、24或25小时
vikingosegundo 2013年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.