基本上,正如标题所说。我想知道如何将 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.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);
这应该是不言自明的。
从 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)
斯威夫特 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];
iOS 8+、OSX 10.9+、Objective-C
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay
value:1
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)
Swift 4.0 (在这个精彩的答案中与 Swift 3.0 相同,只是让像我这样的新手清楚)
let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
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
使用以下函数并使用 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;
}
迅速
var dayComponenet = NSDateComponents()
dayComponenet.day = 1
var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
有用!
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 3.0 非常简单的实现是:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, 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
注意:如果您不知道为什么代码行以感叹号结尾,请在 Google 上查找“Swift Optionals”。
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];
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];
复杂,主要是由于夏令时。
这是一种通用方法,可让您在指定日期添加/减去任何类型的单位(年/月/日/小时/秒等)。
使用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.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)
- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
您可以在哪里使用 NSDate 的seconds
方法60 * 60 * 24 = 86400
在 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 扩展:
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?
对于 Swift 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 *tomorrowDate = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEEE, dd MMM yyyy"];
NSLog(@"%@", [dateFormatter stringFromDate:tomorrowDate]);
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 5 的更新
let nextDate = fromDate.addingTimeInterval(60*60*24)
字符串扩展:转换String_Date > 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(然后再返回)
斯威夫特 2.0
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
在 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
Swift 4,如果您真正需要的是 24 小时轮班(60*60*24 秒)而不是“1 个日历日”
未来:
let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))
过去的:
let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))
只是为了好玩,通过一些扩展和运算符重载,你可以得到一些不错的东西,比如:
let today = Date()
let tomorrow = today + 1.days
, 或者
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
}
代码最少,可以轻松扩展以允许.months
, .years
,等。还可以无缝添加.hours
对减法 ( ) 的支持。-
但是,在运算符的实现中存在强制展开,但+
不确定日历在哪些情况下可以返回 nil 日期。
使用以下代码:
NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];
作为
addTimeInterval
现在已弃用。