tluck234
tluck234

Reputation: 71

C# If statement where date is this month

string month = DateTime.Now.Month.ToString();
string CommandText = "SELECT slocref.slocname, partstuff.quantity, partstuff.currency, partstuff.postingdate" + " FROM partstuff INNER JOIN slocref ON partstuff.sloc = slocref.slocvalue";

This is the code to get date and month.

if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))
{
    if (rdr["slocname"].ToString() == "Answer/Slatwall")
    {
        string quantity = rdr["quantity"].ToString();
        string currency = rdr["currency"].ToString();
        answertotalmonth += float.Parse(currency);
        label100.Text = "$" + answertotalmonth.ToString("#,##0.00");
    }
}

This is just an example of the code that is run by the if statement.

But the if statement needs to get all of the July information and add it up. So from 07/01/2012 to 07/31/2012. I cannot change the SQL because it messes up the rest of the program. I tried to get the current date, add the 0 in front of it, then use a wildcard.

Need a little direction on this if statement.

Let me clarify this post. The "postingdate" value comes from FileHelpers. Importing a text file by fixed width into these values. The postingdate value looks like "07/16/12"

So, I want to get this current month, and then if a postingdate value has that month's value, run the if statement code.

Upvotes: 2

Views: 5149

Answers (2)

Andrew Hagner
Andrew Hagner

Reputation: 804

Not sure I understand you problem correctly but why don't you just match the DataTime's month property:

if( date.Month == month)
{
   //your code...
}

Also like mentioned above, you can parse the text as a date. But if you are just interested in just the month that may not be necessary.

Edit: As mentioned in the comments, you would have to check the year as well. So it would be better to pares as a full DateTime object.

Upvotes: 0

Reacher Gilt
Reacher Gilt

Reputation: 1813

Why would you do this?

 if (Regex.IsMatch(rdr["postingdate"].ToString(), "0" + month + "*"))

If rdr["postingdate"] is supposed to be a date, convert it to a date time and do a sensible comparison.

if(DateTime.TryParse(rdr["postingdate"].ToString(), rdrDateTime))
{
    // proceed as planned
    if (rdrDate.Month == DateTime.Now.Month) 
    {
       // and so on.
    }
}

Upvotes: 1

Related Questions