Ios 如何在NSDate中添加一个月?
如何将月份添加到NSDate对象Ios 如何在NSDate中添加一个月?,ios,iphone,objective-c,nsdate,Ios,Iphone,Objective C,Nsdate,如何将月份添加到NSDate对象 NSDate *someDate = [NSDate Date] + 30Days.....; 您需要使用NSDateComponents: NSDateComponents *dateComponents = [[NSDateComponents alloc] init]; [dateComponents setMonth:1]; NSCalendar *calendar = [NSCalendar currentCalendar]; NSDate *new
NSDate *someDate = [NSDate Date] + 30Days.....;
您需要使用NSDateComponents:
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setMonth:1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *newDate = [calendar dateByAddingComponents:dateComponents toDate:originalDate options:0];
[dateComponents release]; // If ARC is not used, release the date components
您想添加一个“月”还是正好30天?如果是30天,你可以这样做:
// get a date
NSDate *date = [NSDate dateWithNaturalLanguageString:@"2011-01-02"];
// add 30 days to it (in seconds)
date = [date dateByAddingTimeInterval:(30 * 24 * 60 * 60)];
NSLog(@"%@", date); // 2011-02-01
注意:这将不考虑夏令时转换或闰秒。如果需要,请使用@TheEye的答案使用iOS 8和OS X 10.9,您可以使用
NSCalendar添加NSCalendarUnits
:
目标-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *someDate = [cal dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:[NSDate date] options:0];
斯威夫特3
let date = Calendar.current.date(byAdding: .month, value: 1, to: Date())
斯威夫特2
let cal = NSCalendar.currentCalendar()
let date = cal.dateByAddingUnit(.Month, value: 1, toDate: NSDate(), options: [])
例如,要在Swift中向当前日期添加3
个月:
let date = NSCalendar.currentCalendar().dateByAddingUnit(.MonthCalendarUnit, value: 3, toDate: NSDate(), options: nil)!
在Swift 2.0中:
- 新的
选项settype
结构的NSCalendarUnit
允许您更简单地指定.Month
- 采用
options设置类型的参数(如采用NSCalendarOptions
的options:
参数)不能为nil
,因此传入一个空集([]
)表示“无选项”
在Swift 2.0中
let startDate = NSDate()
let dateComponent = NSDateComponents()
dateComponent.month = 1
let cal = NSCalendar.currentCalendar()
let endDate = cal.dateByAddingComponents(dateComponent, toDate: startDate, options: NSCalendarOptions(rawValue: 0))
适用于SWIFT 3.0
这是一个函数,你可以任意减少天数、月份、天数
比如这里,我把当前系统日期的年份减少了100年,你也可以把它改为天,月
只需设置计数器,然后将值存储在数组中,并对该数组执行任何操作
func currentTime(){
let date = Date()
let calendar = Calendar.current
var year = calendar.component(.year, from: date)
let month = calendar.component(.month, from: date)
let day = calendar.component(.day, from: date)
let pastyear = year - 100
var someInts = [Int]()
printLog(msg: "\(day):\(month):\(year)" )
for _ in pastyear...year {
year -= 1
print("\(year) ")
someInts.append(year)
}
print(someInts)
}
如果你想要的行为是增加一个月的时间并考虑到夏令时,其他答案也可以。这会产生如下结果:
01/03/2017 00:00 + 1 month -> 31/03/2017 23:00
01/10/2017 00:00 + 1 month -> 01/11/2017 01:00
01/03/2017 00:00 + 1 month -> 01/04/2017 00:00
01/10/2017 00:00 + 1 month -> 01/11/2017 00:00
然而,我想忽略DST损失或获得的时间,例如:
01/03/2017 00:00 + 1 month -> 31/03/2017 23:00
01/10/2017 00:00 + 1 month -> 01/11/2017 01:00
01/03/2017 00:00 + 1 month -> 01/04/2017 00:00
01/10/2017 00:00 + 1 month -> 01/11/2017 00:00
因此,我检查DST边界是否通过,如果通过,则相应地加上或减去一小时:
func offsetDaylightSavingsTime() -> Date {
// daylightSavingTimeOffset is either + 1hr or + 0hr. To offset DST for a given date, we need to add an hour or subtract an hour
// +1hr -> +1hr
// +0hr -> -1hr
// offset = (daylightSavingTimeOffset * 2) - 1 hour
let daylightSavingsTimeOffset = TimeZone.current.daylightSavingTimeOffset(for: self)
let oneHour = TimeInterval(3600)
let offset = (daylightSavingsTimeOffset * 2) - oneHour
return self.addingTimeInterval(offset)
}
func isBetweeen(date date1: Date, andDate date2: Date) -> Bool {
return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
}
func offsetDaylightSavingsTimeIfNecessary(nextDate: Date) -> Date {
if let nextDST = TimeZone.current.nextDaylightSavingTimeTransition(after: self) {
if nextDST.isBetweeen(date: self, andDate: nextDate){
let offsetDate = nextDate.offsetDaylightSavingsTime()
let difference = offsetDate.timeIntervalSince(nextDate)
return nextDate.addingTimeInterval(difference)
}
}
return nextDate
}
func dateByAddingMonths(_ months: Int) -> Date? {
if let dateWithMonthsAdded = Calendar.current.date(byAdding: .month, value: months, to: self) {
return self.offsetDaylightSavingsTimeIfNecessary(nextDate: dateWithMonthsAdded)
}
return self
}
测试:
为了完整起见,我使用的.asDate()方法
extension String {
static let dateFormatter = DateFormatter()
func checkIsValidDate() -> Bool {
return self.tryParseToDate() != nil
}
func tryParseToDate() -> Date? {
String.dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
return String.dateFormatter.date(from: self)
}
func asDate() -> Date {
return tryParseToDate()!
}
}
适用于swift 3.0
extension Date {
func addMonth(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .month, value: n, to: self)!
}
func addDay(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .day, value: n, to: self)!
}
func addSec(n: Int) -> Date {
let cal = NSCalendar.current
return cal.date(byAdding: .second, value: n, to: self)!
}
}
是否要根据用户选择的“自动计算到日期”添加“月份”或恰好30天、一天或一年
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]
init];
[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:[NSDate date]];
NSDateComponents *dayComponent = [[NSDateComponents alloc]
init];
int changeid = [here number of days intValue];
dayComponent.hour = changeid;
NSCalendar *theCalendar = [NSCalendar currentCalendar];
NSDate *nextDate = [theCalendar
dateByAddingComponents:dayComponent toDate:[dateFormatter
dateFromString:self.fromDateTF.text] options:0];
NSLog(@"nextDate: %@ ...", nextDate);
[self.toDateTF setText:[dateFormatter
stringFromDate:nextDate]];
////月如果在DST更改或闰秒等情况下使用,则此操作将失败。@JamesWebster这是一个很好的观点,我在我的答案中添加了一条注释。低级别的加法/减法秒仍然属于答案之一。你并不总是想遵循DST之类的规则,这取决于日期的用途。不,每个月有30天。这并不能增加30天。它增加了30乘以86400秒,这是完全不同的。这种代码是非常糟糕的建议。在DST转换的情况下,这确实会给出错误的结果。但是闰秒不是问题,因为Unix时间不计算闰秒。您知道如何将现在与命运日期进行比较吗?若要检查是否传递了此日期,请使用NSDate函数compare、earlierDate和laterDate进行日期比较-请参阅NSDate文档:@orazran您可以将日期与以下日期进行比较:[date-TimeIntervalenceDate:otherDate]
,这将以秒为单位返回它们之间的差异(过去日期小于0,未来日期大于0)。如果开始日期为1月31日,您希望得到什么结果?。MonthCalendarUnit
不推荐使用,请使用。CalendarUnitMonth
上述示例正在调用一个方法,而不是访问属性。Swift 3:让date=Calendar.current.date(通过添加:.month,值:1,to:date())这应该是可接受的答案。目前可接受的答案仅为Objective-C且过于冗长。如果我将1月31日加上1个月,它将在3月2日或……,会发生什么。。。?