我如何将一天添加到NSDate?
基本上,如标题所述。 我想知道如何将一天添加到NSDate
。
所以如果是这样的话:
21st February 2011
它会变成:
22nd February 2011
或者如果是:
31st December 2011
它会变成:
1st January 2012.
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);
这应该是不言自明的。
从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)
尝试这个
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]; [offsetComponents release]; [gregorian release];
iOS 8+,OSX 10.9+,Objective-C
NSCalendar *cal = [NSCalendar currentCalendar]; NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay value:1 toDate:[NSDate date] options:0];
使用下面的函数,并使用天参数来获取datedaysAhead / daysBehind只是通过参数为积极的未来的date或负面的前一个date:
+ (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; }
迅速
var dayComponenet = NSDateComponents() dayComponenet.day = 1 var theCalendar = NSCalendar.currentCalendar() var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
基于Andy的答案和作为date扩展的一个有效的Swift 3实现 ,带有更改年份,月份和时间的附加选项:
extension Date { /// Returns a Date with the specified days 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 { var targetDay: Date targetDay = Calendar.current.date(byAdding: .year, value: years, to: self)! targetDay = Calendar.current.date(byAdding: .month, value: months, to: targetDay)! targetDay = Calendar.current.date(byAdding: .day, value: days, to: targetDay)! targetDay = Calendar.current.date(byAdding: .hour, value: hours, to: targetDay)! targetDay = Calendar.current.date(byAdding: .minute, value: minutes, to: targetDay)! targetDay = Calendar.current.date(byAdding: .second, value: seconds, to: targetDay)! return targetDay } /// Returns a Date with the specified days 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 { let inverseYears = -1 * years let inverseMonths = -1 * months let inverseDays = -1 * days let inverseHours = -1 * hours let inverseMinutes = -1 * minutes let inverseSeconds = -1 * seconds return add(years: inverseYears, months: inverseMonths, days: inverseDays, hours: inverseHours, minutes: inverseMinutes, seconds: inverseSeconds) } }
OP所要求的仅用于添加一天的用法将是:
let today = Date() // date is then today for this example let tomorrow = today.add(days: 1)
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];
Swift 3.0非常简单的实现将是:
func dateByAddingDays(inDays:NSInteger)->Date{ let today = Date() return Calendar.current.date(byAdding: .day, value: inDays, to: today)! }
是工作!
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];
你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
seconds
将是60 * 60 * 24 = 86400
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]);
在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! }
函数调用将当前date递增9天
var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9) print(newDate)
函数调用当前date减less80天
newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80) print(newDate)
这是一个通用的方法,可以让你在指定的date添加/减去任何types的单位(年/月/日/小时/秒等)。
使用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
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小时的date。 实际上可能有24个,但是在计算中只用了23:00。
同样的,如果您前进到2013年10月28日,代码将增加25小时,导致date时间为2013-10-28 01:00:00。
很奇怪。
为了增加一天,我正在做的顶部的东西,添加:
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
但是在某些date,这真是一团糟,主要是由于夏令时。
Objective-C,date是一场噩梦。
在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)
为了迅捷2.2:
let today = NSDate() let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit( .Day, value: 1, toDate: today, options: NSCalendarOptions.MatchStrictly)
希望这可以帮助别人!
使用以下代码:
NSDate *now = [NSDate date]; int daysToAdd = 1; NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
如
addTimeInterval
现已被弃用。
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);
我有同样的问题; 使用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]; }
Swift 2.0
let today = NSDate() let calendar = NSCalendar.currentCalendar() let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)