【问题标题】:How to get number of days between two dates objective-c [duplicate]如何获取两个日期之间的天数objective-c [重复]
【发布时间】:2013-08-07 03:57:21
【问题描述】:

我正在尝试制作一个标签,说明距离活动还有多少天。我想计算今天日期和事件日期之间的差异。我正在使用这段代码,它给了我-4600。在我使用今天的日期之前它工作正常。

NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [NSDate date];
    NSDate *endDate = [f dateFromString:end];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];
    return components.day;
return components.day;

【问题讨论】:

  • 你说的一个问题是重复的,我用过那个答案,但它不起作用。
  • 您确认NSDate *endDate = [f dateFromString:end] 返回预期日期了吗? - 字符串end 包含什么?
  • @user1898829 那么你应该在你的问题中提到这一点

标签: ios objective-c nsstring nsdate


【解决方案1】:

默认情况下[NSDate date] 返回日期类似于2013-08-06 08:50:25 +0000 并且您已将格式化程序设置为 yyyy-MM-dd this,因此您必须将 startDate 转换为 yyyy-MM-dd 此表单..

试试这个

NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"];
    NSDate *startDate = [NSDate date];
    NSLog(@"%@",startDate);
    NSDate *endDate = [f dateFromString:end];
    NSLog(@"%@",endDate);


    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];
    return components.day; 

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多