基本上,正如标题所说。我想知道如何在NSDate
上加1天。
如果它是:
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);
这应该是不言自明的。
这是工作!
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 *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];
你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
,其中seconds
将是60 * 60 * 24 = 86400
在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)
这是一种通用方法,允许您在指定日期添加/减去任何类型的单位(年/月/日/小时/秒等)。
使用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
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”。
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中,您可以在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)
对于swift 2.2:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: NSCalendarOptions.MatchStrictly)
希望这有助于某人!
Swift 4,如果您真正需要的是24小时轮班(60 * 60 * 24秒)而不是“1个日历日”
未来:let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去:let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
从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)
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];
复杂,主要是由于夏令时。
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)
使用以下代码:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
如
addTimeInterval
现已弃用。
目标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)
iOS 8 +,OSX 10.9 +,Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay
value:1
toDate:[NSDate date]
options:0];
基于highmaintenance's回答和vikingosegundo's评论的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)
}
}
按OP的要求仅添加一天的用法将是:
let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)
Swift 4.0(与this wonderful answer中的Swift 3.0相同,只是让我这样的新手清楚)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
使用以下函数并使用天数参数来获取日期前/天后面只是将参数传递为未来日期的正数或以前日期的负数:
+ (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)
Swift 3.0非常简单的实现将是:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}