如何向 NSDate 添加 1 天?

发布于 2024-10-18 13:18:17 字数 290 浏览 3 评论 0原文

基本上就如标题所说。我想知道如何向 NSDate 添加 1 天。

因此,如果是:

21st February 2011

它将变成:

22nd February 2011

或者如果是:

31st December 2011

它将变成:

1st January 2012.

Basically, as the title says. I'm wondering how I could add 1 day to an NSDate.

So if it were:

21st February 2011

It would become:

22nd February 2011

Or if it were:

31st December 2011

It would become:

1st January 2012.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

睫毛上残留的泪 2024-10-25 13:18:17

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);

这应该是不言自明的。

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)")

Objective 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);

This should be self-explanatory.

千里故人稀 2024-10-25 13:18:17

从 iOS 8 开始,您可以使用 Swift 1.x 中的 NSCalendar.dateByAddingUnit

示例:

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)

Since iOS 8 you can use NSCalendar.dateByAddingUnit

Example in 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)
兰花执着 2024-10-25 13:18:17

Swift 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];

Swift 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];
離殇 2024-10-25 13:18:17

基于 highmaintenance 答案和 vikingosegundo 的评论。此日期扩展还具有更改年、月和时间的附加选项:

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)

A working Swift 3+ implementation based on highmaintenance's answer and vikingosegundo's comment. This Date extension also has additional options to change year, month and time:

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)
    }

}

Usage for only adding a day as asked by OP would then be:

let today = Date() // date is then today for this example
let tomorrow = today.add(days: 1)
近箐 2024-10-25 13:18:17

iOS 8+、OSX 10.9+、Objective-C

NSCalendar *cal = [NSCalendar currentCalendar];    
NSDate *tomorrow = [cal dateByAddingUnit:NSCalendarUnitDay 
                                   value:1 
                                  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];
情何以堪。 2024-10-25 13:18:17

Swift 4.0(与 这个精彩答案中的 Swift 3.0 相同,只是让像我这样的菜鸟明白)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)

Swift 4.0 (same as Swift 3.0 in this wonderful answer just making it clear for rookies like me)

let today = Date()
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: today)
哥,最终变帅啦 2024-10-25 13:18:17

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

Update for 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
撩起发的微风 2024-10-25 13:18:17

使用下面的函数并使用 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;
}

Use the below function and use days paramater to get the date daysAhead/daysBehind just pass parameter as positive for future date or negative for previous dates:

+ (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;
}
怀里藏娇 2024-10-25 13:18:17

迅速

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)

In swift

var dayComponenet = NSDateComponents()
dayComponenet.day = 1

var theCalendar = NSCalendar.currentCalendar()
var nextDate = theCalendar.dateByAddingComponents(dayComponenet, toDate: NSDate(), options: nil)
潦草背影 2024-10-25 13:18:17

有用!

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];

It works!

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];
层林尽染 2024-10-25 13:18:17

Swift 3.0 非常简单的实现是:

func dateByAddingDays(inDays: Int) -> Date {
    let today = Date()
    return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}

Swift 3.0 very simple implementation would be:

func dateByAddingDays(inDays: Int) -> Date {
    let today = Date()
    return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
凉风有信 2024-10-25 13:18:17

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 Options”。

Swift 4.0

extension Date {
    func add(_ unit: Calendar.Component, value: Int) -> Date? {
        return Calendar.current.date(byAdding: unit, value: value, to: self)
    }
}

Usage

date.add(.day, 3)!   // adds 3 days
date.add(.day, -14)!   // subtracts 14 days

Note: If you don't know why the lines of code end with an exclamation point, look up "Swift Optionals" on Google.

请远离我 2024-10-25 13:18:17
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 *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];
梦途 2024-10-25 13:18:17

昨天和明天的任何日期的简单 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?

Simple Swift extensions for yesterday and tomorrow from any date:

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)!
    }
    
}

I'm force unwrapping the optionals based on advice in the question here:
When does dateByAddingComponents:toDate:options return nil?

z祗昰~ 2024-10-25 13:18:17

向前和向后添加任意天数

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!
}

在 Swift 2.1.1 和 xcode 7.1 OSX 10.10.5 中,您可以使用函数函数调用 将当前日期递增 9 天

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)

函数调用 将当前日期递减 80 天

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
 print(newDate)

In Swift 2.1.1 and xcode 7.1 OSX 10.10.5 ,you can add any number of days forward and backwards using function

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!
}

function call for incrementing current date by 9 days

var newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: 9)
print(newDate)

function call for decrement current date by 80 days

newDate = addDaystoGivenDate(NSDate(), NumberOfDaysToAdd: -80)
 print(newDate)
少女情怀诗 2024-10-25 13:18:17

这是一个通用方法,可让您在指定日期中添加/减去任何类型的单位(年/月/日/小时/秒等)。

使用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

Here is a general purpose method which lets you add/subtract any type of unit(Year/Month/Day/Hour/Second etc) in the specified date.

Using 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
丢了幸福的猪 2024-10-25 13:18:17
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];

复杂,主要是由于夏令时。

NSDateComponents *dayComponent = [[[NSDateComponents alloc] init] autorelease];
dayComponent.day = 1;

NSCalendar *theCalendar = [NSCalendar currentCalendar];
dateToBeIncremented = [theCalendar dateByAddingComponents:dayComponent toDate:dateToBeIncremented options:0];

Ok - I thought this was going to work for me. However, if you use it to add a day to the 31st March 2013, it'll return a date that has only 23 hours added to it. It may well actually have the 24, but using in calculations has only 23:00 hours added.

Similarly, if you blast forward to 28th Oct 2013, the code adds 25 hours resulting in a date time of 2013-10-28 01:00:00.

In order to add a day I was doing the thing at the top, adding the:

NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

Complicated, principally due to daylight saving.

蓝戈者 2024-10-25 13:18:17

您可以使用 NSDate 的方法 - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds 其中 seconds 将为 60 * 60 * 24 = 86400

You can use NSDate's method - (id)dateByAddingTimeInterval:(NSTimeInterval)seconds where seconds would be 60 * 60 * 24 = 86400

云朵有点甜 2024-10-25 13:18:17

您可以快速扩展以在 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)

In swift you can make extension to add method in 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)
    }
}

you can use this as

NSDate().addNoOfDays(3)
但可醉心 2024-10-25 13:18:17
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];
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]);
谈情不如逗狗 2024-10-25 13:18:17

对于 swift 2.2:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day,
        value: 1,
        toDate: today,
        options: NSCalendarOptions.MatchStrictly)

希望这对某人有帮助!

for swift 2.2:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar().dateByAddingUnit(
        .Day,
        value: 1,
        toDate: today,
        options: NSCalendarOptions.MatchStrictly)

Hope this helps someone!

假情假意假温柔 2024-10-25 13:18:17

快速 5 的更新

let nextDate = fromDate.addingTimeInterval(60*60*24)

update for swift 5

let nextDate = fromDate.addingTimeInterval(60*60*24)
只是一片海 2024-10-25 13:18:17
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 *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);
笑叹一世浮沉 2024-10-25 13:18:17

我也遇到了同样的问题;使用 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];
}

I had the same problem; use an extension for 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];
}
杀お生予夺 2024-10-25 13:18:17

斯威夫特2.0

let today = NSDate()    
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)

Swift 2.0

let today = NSDate()    
let calendar = NSCalendar.currentCalendar()
let tomorrow = calendar.dateByAddingUnit(.Day, value: 1, toDate: today, options: NSCalendarOptions.MatchFirst)
要走就滚别墨迹 2024-10-25 13:18:17

Swift 4,如果您真正需要的是 24 小时轮班(60*60*24 秒)而不是“1 个日历日”

未来:
let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))

过去:
让 dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))

Swift 4, if all you really need is a 24 hour shift (60*60*24 seconds) and not "1 calendar day"

Future:
let dayAhead = Date(timeIntervalSinceNow: TimeInterval(86400.0))

Past:
let dayAgo = Date(timeIntervalSinceNow: TimeInterval(-86400.0))

方觉久 2024-10-25 13:18:17

字符串扩展:转换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

参考:来自多个问题

如何向 NSDate 添加 1 天?< /a>
数学函数将正整数转换为负数,将负数转换为正数?


将 NSString 转换为 NSDate(然后再转换回来)

String extension: Convert 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)!
  }
}

Date extension: Convert Date > String

extension Date{
 func DateConvert(_ newFormat:String)-> String{
    let formatter = DateFormatter()
    formatter.dateFormat = newFormat
    return formatter.string(from: self)
 }
}

Date extension: Get +/- Date

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!
 }
}

Usage:

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

reference: from multiple question

How do I add 1 day to an NSDate?

math function to convert positive int to negative and negative to positive?

Converting NSString to NSDate (and back again)

假装不在乎 2024-10-25 13:18:17

在 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

In Swift 4 or Swift 5, you can use 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)

output:

Current date: 2020-03-02
yesterday date: 2020-03-01
挽清梦 2024-10-25 13:18:17

只是为了好玩,通过一些扩展和运算符重载,您最终可以得到一些不错的东西,例如:

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 等。还可以无缝添加对减法 (-) 的支持。

不过,在 + 运算符的实现中存在强制展开,但不确定在什么情况下日历可以返回零日期。

Just for fun, with a few extensions and operator overloads, you can end up with something nice, like:

let today = Date()
let tomorrow = today + 1.days

, or

var date = Date()
date += 1.months

Below is the support code:

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
}

The code is minimal, and can be easily extended to allow .months, .years, .hours, etc. Also support for subtraction (-) can be seamlessly added.

There is a forced unwrap, though, within the implementation of the + operator, however not sure under which circumstances can the calendar return a nil date.

挽容 2024-10-25 13:18:17

使用以下代码:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

现在

addTimeInterval

已弃用。

Use following code:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

As

addTimeInterval

is now deprecated.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文