基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
基本上,就像标题说的那样。我想知道如何添加1天的NSDate。
如果它是:
21st February 2011
它将变成:
22nd February 2011
或者如果它是:
31st December 2011
它将变成:
1st January 2012.
斯威夫特5
let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)
objective - 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];
你可以使用NSDate的方法- (id)dateByAddingTimeInterval:(NSTimeInterval)秒,其中秒为60 * 60 * 24 = 86400
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);
这应该是不言而喻的。
使用以下代码:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
As
addTimeInterval
现在已弃用。
使用下面的函数,并使用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;
}
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 *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 *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);
从iOS 8开始,你可以使用NSCalendar.dateByAddingUnit
Swift 1.x中的示例:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.CalendarUnitDay,
value: 1,
toDate: today,
options: NSCalendarOptions(0)
)
斯威夫特2.0:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
.dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: []
)
斯威夫特3.0:
let today = Date()
let tomorrow = 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];
在斯威夫特
var dayComponenet = NSDateComponents()
dayComponenet.day = 1
var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
我也有同样的问题;使用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];
}
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.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)
它的工作原理!
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];
这是一个通用的方法,它允许您在指定的日期中添加/减去任何类型的单位(年/月/日/小时/秒等)。
使用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 2.2:
let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: NSCalendarOptions.MatchStrictly)
希望这能帮助到一些人!
基于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.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
Swift 3.0非常简单的实现将是:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
Swift 4,如果你真正需要的是24小时轮班(60*60*24秒)而不是“1个日历天”
未来: let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去: let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
Swift 4.0(在这个精彩的答案中与Swift 3.0相同,只是为了让像我这样的新手清楚)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
斯威夫特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
注意:如果你不知道为什么代码行以感叹号结尾,可以在谷歌上查找“Swift optional”。
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
在Swift 4或Swift 5中,你可以使用like bellow:
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
字符串扩展:转换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(然后再转换回来)
只是为了好玩,通过一些扩展和操作符重载,你可以得到一些不错的东西,比如:
let today = Date()
let tomorrow = today + 1.days
, or
var date = Date()
date += 1.months
下面是支持代码:
extension Calendar {
struct ComponentWithValue {
let component: Component
let value: Int
}
}
extension Int {
var days: Calendar.ComponentWithValue {
.init(component: .day, value: self)
}
var months: Calendar.ComponentWithValue {
.init(component: .month, value: self)
}
}
func +(_ date: Date, _ amount: Calendar.ComponentWithValue) -> Date {
Calendar.current.date(byAdding: amount.component, value: amount.value, to: date)!
}
func +(_ amount: Calendar.ComponentWithValue, _ date: Date) -> Date {
date + amount
}
func +=(_ date: inout Date, _ amount: Calendar.ComponentWithValue) {
date = date + amount
}
代码是最少的,并且可以很容易地扩展到允许.月,.年,.小时等。还可以无缝添加对减法(-)的支持。
虽然在+操作符的实现中有一个强制的展开,但是不确定在哪种情况下日历可以返回nil日期。
简单的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)!
}
}
我在这里根据问题中的建议强制展开可选选项: 何时dateByAddingComponents:toDate:options返回nil?