【问题标题】:How to calculate no of days in current date in iphone [closed]如何在iphone中计算当前日期的天数[关闭]
【发布时间】:2013-12-11 13:59:50
【问题描述】:

我正在开发一个 iPhone 应用程序。

如何在 iPhone 中获取从当年第一个日期到当前日期的天数。

我试过这段代码: NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:self toDate:aDate options:0];

return [components day];

但是当我给出的日期是:jan /01/2013 todate 是:dec/12/31 我得到了 363 天。但是我们有365天。

请帮我解决这个问题。谢谢。

【问题讨论】:

  • 什么????????????当你把我搞糊涂的时候,我理解到“iPhone 中的第一个日期到当前日期”。
  • 请告诉我们您已经尝试过什么以及该代码有什么问题!
  • @popeye 你有我的问题吗?
  • 我的第一印象是你想知道从 x 天(2013 年 1 月 1 日)到 y 天(今天)有多少天。那是对的吗?如果是这样,请分享您的尝试,让您的问题更有意义。
  • @HAS Friend 我需要获取从当年第一个日期到当前日期的天数。我需要从当年获取当前日期总天数。

标签: ios iphone ios7


【解决方案1】:

NSCalendar是你的朋友:

NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar currentCalendar];
NSUInteger days = [cal ordinalityOfUnit:NSDayCalendarUnit
                                 inUnit:NSYearCalendarUnit forDate:now];

今天(2013 年 12 月 11 日)的结果:345

【讨论】:

  • 效果很好,谢谢朋友
  • @user1547937:如果我的回答有帮助,如果您通过单击复选标记“接受”它,那就太好了。
【解决方案2】:

使用此代码,您可以获得两个日期之间的天数。

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [gregorian components:NSDayCalendarUnit
                                                fromDate:date

                                                  toDate:toDate
                                                 options:0];
    NSInteger days = [components day];
    ;
    return days;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多