Search code examples
objective-cswiftnsdatensdateformatternscalendar

How can I determine if the current date is within/outside a range of two dates that don't include a year?


So I have an object (Activity) where I allow users to select start date and an expiry date for an activity.

The user is basically a center/centre that provides activities for the public.

They have the option of making these activities seasonal. So for example an activity could run from Feb 01 to June 22. I use the current date along with a bunch of code to determine if the activity is in season or not.

So for example I check if the current date 271014 is greater than the start date 020114 and less than the expiry date 062214. If it is then it means the date is in range.

The issue:

I've had to make changes, so now the user must select a month and day only. This is fine until they select something like Nov 01 to Feb 28. These dates would be in the format 1101 and 2802.

Without the year this obviously gives me different results. With the year I would have been able to determine that the expiry date Feb 28 was the year after the start date and not the same year. Then when working out if the current date was within the start date and expiry date I'd get expected results. Without the year the expiry date is now actually not greater than the start date even though it should be.

What I'm currently doing

How do I solve this issue? All I really need is to allow a user to set a start date and an expiry. The activity will show up in a table view only when the current date is in range.

If only an expiry date is selected then the activity will remain active until that expiry date has been reached. Even if I set and expiry date for Feb 28 and we're in November. The same need applies to the start date too.

Would appreciate some insight here.

Thanks for your time.


Solution

  • Here my suggestion (in pseudo-code): Convert all dates to strings in the format "MMdd", in your example

    startDate   = "1101"  // November 1
    expiryDate  = "0228"  // February 28
    currentDate = "1027"  // October 27
    

    If startDate <= expiryDate then the range is within the same year and you can check the current date with

    if (startDate <= currentDate && currentDate <= expiryDate) ...
    

    Otherwise the range starts in one year and ends in the next year, and you check with

    if (currentDate >= startDate || currentDate <= expiryDate) ...