【问题标题】:Date components day difference between two dates wrong for today and tomorrow今天和明天的两个日期之间的日期组件天差错误
【发布时间】:2014-07-28 19:53:18
【问题描述】:

如果到期日实际上是今天或明天,我想在标签中显示“今天”或“明天”,其余部分以“dd-mm-yyy”格式显示。

除了以下事实(鉴于今天是 6 月 7 日)之外,一切都几乎完美无缺:

  • 如果我将截止日期设置为今天(6 月 7 日)或明天(6 月 8 日),标签将更新为文本“今天”。
  • 如果我将截止日期设置为后天(6 月 9 日),它会显示“明天”。

这是我的代码:

- (void)configureDueLabelForCell:(UITableViewCell *)cell withChecklistItem:(ChecklistItem *)item
{
    UILabel *label = (UILabel *)[cell viewWithTag:1002];

    if (item.shouldRemind) {
        int difference = [self dateDiffrenceToDate:item.dueDate];
        if (difference == 0) {
            label.text = @"Today";
        } else if (difference == 1) {
            label.text = @"Tomorrow";
        } else {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
           // [formatter setDateStyle:NSDateFormatterMediumStyle];
            [formatter setDateFormat:@"dd-MM-yyyy"];
            label.text = [formatter stringFromDate:item.dueDate];
        }

    } else {
        label.text = @"";
    }
}

-(int)dateDiffrenceToDate:(NSDate *)dueDate
{
    // Manage Date Formation same for both dates
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [NSDate date];
    NSDate *endDate = dueDate;


    unsigned flags = NSDayCalendarUnit;
    NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

    int dayDiff = [difference day];

    return dayDiff;
}

我也试过了:

//    NSDate *startDate = [NSDate date];
//    NSDate *endDate = dueDate;
//    
//    NSTimeInterval secondsBetween = [endDate timeIntervalSinceDate:startDate];
//    
//    int numberOfDays = secondsBetween / 86400;
//    NSLog(@"numberofdays: %d", numberOfDays);
//
//    return numberOfDays;

【问题讨论】:

    标签: ios cocoa-touch date time nsdatecomponents


    【解决方案1】:

    来自https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DatesAndTimes/Articles/dtCalendricalCalculations.html#//apple_ref/doc/uid/TP40007836-SW1

    "... 此方法将计算结果截断为提供的最小单位。例如,如果 fromDate: 参数对应于 2010 年 1 月 14 日晚上 11:30,而 toDate: 参数对应于 Jan 15, 2010年8:00 AM,两个日期之间只有8.5小时,如果你问天数,你得到0,因为8.5小时小于1天。可能有应该是1天的情况。您必须确定用户在特定情况下期望的行为。如果您确实需要计算返回天数,由两个日期之间的午夜数计算,您可以使用类似于 NSCalendar 的类别清单 13 中的一个。”

    【讨论】:

    • 哦..现在说得通了..谢谢..有什么办法可以让我只比较日期而不是时间?
    • 或者计算直到午夜的小时数以及直到到期日的小时数。如果距离午夜的时间更短,则截止日期是明天。
    • 经过反思,如果您在结果中计算小时,则截断应该发生在小时级别而不是日级别,您的问题就会消失。另外,您不必担心在午夜之前或之后发生的事件。试试看!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多