如何在NSDate中添加1天?

时间:2011-02-21 15:28:02

标签: objective-c swift date cocoa-touch nsdate

基本上,正如标题所说。我想知道如何在NSDate添加1天。

所以如果是:

21st February 2011

它会变成:

22nd February 2011

或者如果是:

31st December 2011

它会变成:

1st January 2012.

29 个答案:

答案 0 :(得分:686)

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

这应该是不言自明的。

答案 1 :(得分:244)

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

答案 2 :(得分:54)

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

针对Swift 5进行了更新

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

答案 3 :(得分:33)

iOS 8 +,OSX 10.9 +,Objective-C

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

答案 4 :(得分:23)

工作 Swift 3&基于highmaintenance's回答和vikingosegundo's评论的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)
    }

}

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

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

答案 5 :(得分:21)

Swift 4.0 (与this wonderful answer中的Swift 3.0相同,只为我这样的新手明确表示)

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

答案 6 :(得分:12)

使用以下功能并使用天数参数来获取日期天数/天后面只是将参数传递为未来日期的正数或以前日期的负数:

+ (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;
}

答案 7 :(得分:10)

在swift中

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

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

答案 8 :(得分:8)

Swift 3.0非常简单的实现将是:

callback

答案 9 :(得分: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];

答案 10 :(得分: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];

答案 11 :(得分:4)

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

答案 12 :(得分:4)

Swift 4更新:

arr = np.arange(6).reshape(2, 3)

print(arr.data.contiguous)  # True
print(arr.data.c_contiguous)  # True
print(arr.data.f_contiguous)  # False

答案 13 :(得分: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)

答案 14 :(得分:3)

Swift 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”。

答案 15 :(得分:3)

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

使用 Swift 2.2

List<string> lastNames = db.Names.Select(q => q.LastName).ToList();

答案 16 :(得分:2)

在swift中,您可以在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)

答案 17 :(得分: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]);

答案 18 :(得分:1)

对于swift 2.2:

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

希望这有助于某人!

答案 19 :(得分:1)

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

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

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

答案 20 :(得分:1)

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

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

答案 21 :(得分:1)

更新迅速5

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

答案 22 :(得分:0)

Swift 2.0

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

答案 23 :(得分: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];
}

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

答案 25 :(得分:0)

迅速3+:尝试使用此常见扩展程序

extension Date {
    var startOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 1, to: sunday)
    }

    var endOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 7, to: sunday)
    }

    var yesterdayDate: Date? {
        return NSCalendar.current.date(byAdding: .day, value: -1, to: noon)!
    }

    var tommorowDate: Date? {
        return NSCalendar.current.date(byAdding: .day, value: 1, to: noon)!
    }

    var previousDate: Date? {
        let oneDay:Double = 60 * 60 * 24
        return self.addingTimeInterval(-(Double(oneDay)))
    }

    var nextDate: Date? {
        let oneDay:Double = 60 * 60 * 24
        return self.addingTimeInterval(oneDay)
    }

    var noon: Date {
        return NSCalendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
    }

    var month: Int {
        return Calendar.current.component(.month,  from: self)
    }
}

答案 26 :(得分:0)

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

TServerOutput

输出:

    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)

答案 27 :(得分: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

参考:来自多个问题
How do I add 1 day to an NSDate?
math function to convert positive int to negative and negative to positive?
Converting NSString to NSDate (and back again)

答案 28 :(得分:-1)

使用以下代码:

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

作为

addTimeInterval

现已弃用。