基本上如标题所述。我想知道如何将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.
Answers:
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);
这应该是不言自明的。
dateByAddingComponents
通话的最后一个参数更改为NSCalendarOptions(rawValue: 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)
date.add(.days, 1)
吗?*进行并建立扩展程序
extension Date { func adding(_ component: Calendar.Component, _ value: Int) -> Date? { return Calendar.current.date(byAdding: component, value: value, to: self) } }
用法Date().adding(.day, 1) // "Jun 6, 2019 at 5:35 PM"
已为Swift 5更新
let today = Date()
let nextDate = Calendar.current.date(byAdding: .day, value: 1, to: today)
目标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];
一个基于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)
let foo = Date().add([.calendar: 1, .yearForWeekOfYear: 3]
我在答案中添加替代解决方案一样。感谢您的建议,@ vikingosegundo!
Swift 4.0(在这个出色的答案中与Swift 3.0相同,只是让像我这样的菜鸟清楚了)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
使用以下函数并使用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;
}
这是工作!
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
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];
复杂,主要是由于夏令时。
60*60*24 + 1
由于leap秒而变长。日期必须涵盖所有这一切,因此可可的日期处理实际上很棒!
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]);
您可以迅速扩展以在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)
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 4或swift 5中,您可以像下面这样使用:
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(然后再次返回)
使用以下代码:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
如
addTimeInterval
现在已弃用。