【问题标题】:iOS one month from current Date.iOS 从当前日期起一个月。
【发布时间】:2013-10-12 17:01:01
【问题描述】:

我试图从当前日期开始一个月。

以下是我所拥有的并且正在返回:4027-09-24 16:59:00 +0000。 currentDate 是对的。这是怎么回事?

// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMonthCalendarUnit | NSDayCalendarUnit | NSYearCalendarUnit fromDate:currentDate];
dateComponents.month = dateComponents.month + 1;
NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month);

【问题讨论】:

  • 您的代码添加 2013 年,11 个月,... 到当前日期。

标签: ios date calendar nsdate nscalendar


【解决方案1】:

试试这个:

// Get todays date to set the monthly subscription expiration date
NSDate *currentDate = [NSDate date];
NSLog(@"Current Date = %@", currentDate);

NSDateComponents *dateComponents = [NSDateComponents new];
dateComponents.month = 1;

NSDate *currentDatePlus1Month = [[NSCalendar currentCalendar] dateByAddingComponents:dateComponents toDate:currentDate options:0];
NSLog(@"Date = %@", currentDatePlus1Month);

【讨论】:

  • 谢谢兄弟,原来如此!
【解决方案2】:
NSDate *currentDate = [NSDate date];

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDateComponents* components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:currentDate]; 
  // Get necessary date components

[components month]; //gives you month

[components day]; //gives you day

[components year]; //gives you year

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多