ios - 如果今天是本月的最后一天,如何添加日期。?

标签 ios iphone macos cocoa nsdate

我遇到了一个问题,我需要在 7 天前创建一个步进器。我为此编写了代码,但如果是一个月的最后几天,它将在同月继续,而不是在下个月也应该更改。 当年需要执行同样的案例。

例如,如果今天是 2016 年 12 月 30 日,那么通过添加 7 天,它需要更改为 2017 年 1 月 7 日。提前致谢。

最佳答案

试试这个。在这里,我从特定日期开始添加了 7 天。

    // Enter current date
    NSString *currentDate = @"2016-12-30";

    // Set number of days to add
    int addDaysCount = 7;

    // Set date formatter
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    // Convert string to NSDate
    NSDate *dateFromString = [dateFormatter dateFromString:currentDate];

    // Initialize date component
    NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
    [dateComponents setDay:addDaysCount];

    // Retrieve date with increased days count
    NSDate *newDate = [[NSCalendar currentCalendar]
                       dateByAddingComponents:dateComponents
                       toDate:dateFromString options:0];

    NSLog(@"Current date: %@", [dateFormatter stringFromDate:dateFromString]);
    NSLog(@"Updated date: %@", [dateFormatter stringFromDate:newDate]);

关于ios - 如果今天是本月的最后一天,如何添加日期。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39655058/

相关文章:

c# - 如何使用 Xamarin Forms Shell 在 iOS 中的 Tabbar 行和图标之间添加空格?

ios - 如何从自定义 TableViewCell 切换到另一个 ViewController (Swift)

iphone - 更改数组中对象的顺序而不调用它

ios - 当已经有新帧时如何跳过 didReceiveFrame ?

iphone - 获取 NSFileWrapper 的路径

c - macOS上使用什么时钟返回SO_TIMESTAMP的值?

ios - 带有CoreData的RestKit避免了MOC的困惑

ios - PaintCode 表达式中的引用封闭框架

iphone - UIImageViews 和相册的相关 View Controller

MacOS : find out if a process (given a PID) is running in 32bit or in 64bit Intel mode