tags:

views:

72

answers:

3

So I am using a scripting language with c++-like syntax, and I am trying to think of the best way to check if a date is within range. The problem I am running into is that if the current day is in a new month, the check is failing.

Here is what my code looks like:

if(iMonth >= iStartMonth && iMonth <= iEndMonth)
{
    if(iDay >= iStartDay && iDay <= iEndDay)
    {
        if(iYear >= iStartYear && iYear <= iEndYear)
        {
                bEnabled = true;
                return;

When I have something like this:

    Start date: 3 27 2010
    End Date: 4 15 2010
    Current Date: 3 31 2010

The day check fails because if (iDay <= iEndDay) does not pass. The scripting language doesn't have a lot of time related functions, and I can't compare timestamps because I'm allowing users to put like "03:27:2010" and "04:15:2010" as start/end dates in a config file. I'm assuming I am just not thinking straight and missing an easy fix.

+1  A: 

You should really use boost::DateTime instead of attempting to rewrite the wheel (which when the wheel is a date/time framework it's not as trivial as it may seem). This only if the code you pasted is C++ and not your scripting language (it wasn't clear). Also may I suggest to use Lua instead? :)


Anyway the problem is here:

if(iDay >= iStartDay && iDay <= iEndDay)

You should only check this if iMonth == iStartMonth, and the same for the end month. Otherwise iDay = 31, iEndDay = 15 and 31 <= 15 will fail.

Also you should check for the year first, then the month, then the day.

Andreas Bonini
Thank you. LUA isn't an option, the game mod uses Pawn which is fine, it is just a bit lacking in some areas.
Brett Powell
+2  A: 

You can convert all dates to a strings in YYYY-MM-DD format and then do lexicographical compares.

sth
You could even eliminate the dashes - they aren't adding anything to the comparison.
Mark Ransom
A: 
Norman Ramsey