检查日期是否在范围之间 [英] checking if date is between range

查看:49
本文介绍了检查日期是否在范围之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 UICollectionView 的自定义日历设置,我有一个保存 30 天日期的数组.我想要做的是找出一个值是否在当前日期和它之前的 7 天之间.如果是我需要它做某事.我无法弄清楚我做错了什么.这是我目前所拥有的:

I have a custom calendar setup using a UICollectionView and I have an array that hold dates through 30 days. What I am trying to do is find out if a value is between the current date and 7 days before it. If it is I need it to do something. I cannot figure out what I am doing wrong. Here is what I have so far:

    NSDateFormatter *df = [NSDateFormatter new];
    [df setDateFormat:@"MM-dd-yy"];
    NSdate *date = [NSDate date];
    NSDate *newCurrentDate = [date dateByAddingTimeInterval:+14*24*60*60];
    NSDate *sevenDaysBeforeCurrent = [date dateByAddingTimeInterval:-7*24*60*60];




    if([[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:newCurrentDate]] == NSOrderedAscending && [[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:sevenDaysBeforeCurrent]] == NSOrderedDescending )
    {

            UIImage *buttonImage = [UIImage imageNamed:@"dates.png"];
            [myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];

    }

它所做的是更改 newCurrentDate 之前的每个日期的图像,而不仅仅是前 7 个.谁能看到我做错了什么?

What it does is change the image of every date before the newCurrentDate instead of just the previous 7. Can anyone see what I am doing wrong?

这里是数组的初始化:

myDays = [[NSMutableArray alloc] init];
    NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
    NSDate *today = [NSDate date];
    date = [NSDate date];




    for (int i = 0; i < 31; i++)
    {
        NSDateComponents *comps = [[NSDateComponents alloc]init];
        [comps setDay:i];
        [myDays addObject:[cal dateByAddingComponents:comps toDate:today options:0]];
    }

推荐答案

尝试以下方法:

NSDate *currentDate = [NSDate date];
NSDate *dateSevenDaysPrior = [currentDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)];
NSDate *someDate = [currentDate dateByAddingTimeInterval:-(3 * 24 * 60 * 60)]; // adjust as you like

if (([dateSevenDaysPrior compare:someDate] != NSOrderedDescending) &&
    ([someDate compare:currentDate] != NSOrderedDescending))
{
    NSLog(@"date is in range");
}
else
{
    NSLog(@"date is not in range");
}

这假设您提供的内容(someDate 在此示例中代表什么)确实是 NSDate 的实例.

This assumes that what you're providing (what someDate is standing for in this example) really is an instance of NSDate.

这篇关于检查日期是否在范围之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆