C# If statement where date is this month - c#

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.

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.
}
}

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.

Related

String comparison fails even when visually checked

I added a function to my application recently that reads a date from a downloaded file and finds the difference in days between current date and the date from the file. When done, it is displayed in a label in one of my forums.
There is an exception: if the string in the file equals "Lifetime", it should not process it as a date and follow alternate logic. But when I try to check if the string is "Lifetime", it does not return true, even if the string = "Lifetime".
EDIT: I fixed the FormatException with help from Nisarg. Now, my labels aren't changing to the values. This is the problem.
EDIT2: I feel stupid. I found out that I was initiating Main twice in one function, then using main1 to switch between forms and main to set the labels.
This is why the labels weren't working right. Thanks Nisarg and all other contributors.
Code example:
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
if (subScript == "Lifetime") // it bypasses this, apparently blank
{
main.daysLeftLabel.Text = "Expires: Never";
}
if (subScript != "Lifetime") //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString(((Convert.ToDateTime(subScript)) - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
While using files you often get trailing blank spaces or newline characters. Try trimming the string before comparing it to Lifetime:
subScript = subScript.Trim().Trim(Environment.NewLine.ToCharArray());
Another (less likely) problem could be with the comparison itself. In C# the comparison in case-sensitive. So if you're comparing lifetime with Lifetime they are considered unequal. You should rather use case-insensitive comparison:
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
OR
if(subScript.ToLower() == "lifetime")
You could also check if the subScript you are getting from the file is a valid date or not using DateTime.TryParse.
string subScript = File.ReadAllText(Path.GetTempPath() + txtUsername.Text + ".txt");
Main main = new Main();
double dSubLeft;
main.dateLabel.Text = subScript;
DateTime subScriptDate;
if(!DateTime.TryParse(subScript, out subScriptDate))
{
main.daysLeftLabel.Text = "Expires: Never";
}
else //Goes here and throws error saying subScript is not valid DateTime
{
dSubLeft = Math.Round(Convert.ToDouble(Convert.ToString((subScriptDate - DateTime.Now).TotalDays)));
string sSubLeft = Convert.ToString(dSubLeft);
main.daysLeftLabel.Text = "Expires: " + sSubLeft + " Days";
}
I think it is because main is the starting point of a program in C#, make another methodname if you donĀ“t want it to reset things from where the program is supposed to start from
That is my guess only, make a breakpoint in the beginning of your code and check through what info you get from each row in the code
Almost certainly, the actual content of the string is not actually the string "Lifetime". Probably because of white-space on either side. Try trimming.
Relevant edit:
if (subscript.Trim() == "Lifetime")
{
main.daysLeftLabel.Text = "Expires: Never";
}
else // don't retest for the opposite condition
{
...
As you can see, this thing is awfully fragile, because the string could still be many things that aren't a valid DateTime. Smells like homework, but there you go...
i think you should use
if(string.Equals(subScript, "Lifetime", StringComparer.OrdinalIgnoreCase))
{
//statement
}
else
{
//statement
}

How to split a value and increment a part using c#

I have the following code:
int value = 0;
int day = 0;
int record = db.Orders.Where(x => x.Order_Date.Value.Year == DateTime.Now.Year
&& x.Order_Date.Value.Month == DateTime.Now.Month
&& x.Order_Date.Value.Day == DateTime.Now.Day).Count();
if (record > 0)
{
value = int.Parse(db.Orders.OrderByDescending(x => x.Order_Id).Select(y => y.Order_Id).First().ToString());
value += 1;
}
else
{
day = Convert.ToInt32(DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy"));
value = day + 0001;
}
I want to save the order id in ddmmyysomevalue like 0501150001 if it is first order.
I do have above code but how to split 0501150001 like 050115 and 0001 and then increment 0002 for the next order and make it 0501150000 thereby 0501150009 to 0501150010 and make the above code meaningful.
You have to store value in string.
For number you have to use format like this.
int value = 1;
String finalnumber = DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy") + value.ToString("0000");
Console.WriteLine(value.ToString("0000")); // to format number only.
// to get as a number
long finalnumber = Convert.ToInt64( DateTime.Now.ToString("dd") + DateTime.Now.ToString("MM") + DateTime.Now.ToString("yy") + value.ToString("0000"));
Because the code you've shown will always have the same length for each part of the Order Id you can split by length and cast the final part to an integer. Bear in mind this will break if any part of the orderId starts using a different length in future:
// get the date part of the string by length
string datePart = orderId.Substring(0, 6);
// get the count part of the string by length and cast to integer
int countPart = Int32.Parse(orderId.Substring(6, 4));
// increment the count
countPart++;
// convert the count back into a string and pad with zeroes to get length 4
string newCount = countPart.ToString().PadLeft(4, '0');
// combine with the datepart to get the new OrderId
string newOrderId = datePart + newCount;
This should point you in the right direction...
int existingTodayOrdersCount = db.Orders
.Where(x => x.Order_Date.Value.Date == DateTime.Now.Date)
.Count();
string newOrderId = string.Format(
"{0:yyMMdd}{1:0000}",
DateTime.Now,
existingTodayOrdersCount + 1);
When comparing two dates you can just call .Date on your DateTime objects. No need to explicitly compare the year, month and day
To concatenate numeric values or format a numeric value with leading zeros you need to treat it as a string
The above code uses a custom numeric format string (0000) and a custom date and time format string (yyMMdd).
Be aware of subtle bugs though...
What if you already have 9999 orders today?
What if this code is executed at midnight (could DateTime.Now wrap to the next day part way through execution?)
What if you delete an order record from the database, in which case newOrderId might clash with an existing order?

Return DB results within Date Range

In my view, I have an input and select tags for the user to enter a start and end date.
When submitted, The controller will search the Model/Database and return entries within the above range.
In my DB, the start and end dates are written as "nvarchars" and in my controller they are taken as strings
Code and Images for reference:
public ActionResult timePeriod(string time)
{
//Start: month, day, year End: month, day, year --> Numeric values
string[] times = time.Split(',');
string start = times[0] + " " + times[1] + " " + times[2];
string end = times[3] + " " + times[4] + " " + times[5];
//Sample code to test the start date
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Contains(start)).ToList();
}
a snippet of the Database values:
Are there any LINQ expression to do this?
As the dates are strings, you've nothing better other than using what you have suggested already:
viewModel.Tasks = db.Tasks.Where(s => s.StartTime.Equals(start)).ToList();
I would use Equals as that will be quicker for you. Using Contains is basically like doing a T-SQL LIKE which is much slower.
SELECT *
FROM Table
WHERE StartDate LIKE 'blah'
Using Equals will result in the following equivalent:
SELECT *
FROM Table
WHERE StartDate = 'blah'
Which is much more efficient.

Javascript to validate start date and end date in asp.net

I have written a JS that should check that start date is less than end date. If not, alert should be thrown
The JS is written as;
function DateValidation(startDate, EndDate) {
debugger;
var stdate = startDate;
var enddate = EndDate;
if (stdate!= '' && enddate!='') {
if (stdate > enddate) {
alert('Start date cannot be greater than end date');
return false;
}
else {
return true;
}
}
}
This JS gets fired when i am clicking a button as "Show Report".
Problems that i am facing
JS doesn't validate the date correctly. What am i missing? i am passing date from the textbox
The JS doesn't fired up when clicking button for the first time. it fires when clicking the button second time
Plus, i have registered the JS as below;
btnShowReport.Attributes.Add("onclick", "return DateValidation('" + txtStartDate.Text + "', '" + txtEndDate.Text + "');");
Is the above code correct? What is the correct place to register the JS?
Please guide.. thanks!
You need to parse the string values to dates
if (startDate!= '' && EndDate!='') {
var stdate = Date.parse(startDate);
var enddate = Date.parse(EndDate);
if (stdate > enddate) {
alert('Start date cannot be greater than end date');
return false;
}
else
{
return true;
}
}
Without further code it's hard to tell why your button only fires the event on the second click. Is your button disabled to start with?
Use Date.parse. What you are doing is checking whether a string is greater than another string.
Also the script will take only whatever is there at the first time in txtStartDate.Text, txtEndDate.Text EVERY time the script runs.
Why? You have not correctly understood server side and client side execution.
This line in your code,
btnShowReport.Attributes.Add("onclick", "return DateValidation('" + txtStartDate.Text + "', '" + txtEndDate.Text + "');");
registers the script to the page passing the text in those text boxes.
You have assumed that each time the text changes in the text box, the method will take the new values and do the date calculation.
However your script would look something like this, assuming the two text boxes are empty when the page is loaded. You can verify this by checking the page source.
<inputid="btnShowReport" ... onclick="return DateValidation('','')>
Because JavaScript is run at client side, the server is not contacted each time to get the current values of those text boxes.
What you can do is pass the text boxes it self to the method. Something like
return DateValidation(txtStartDate.ClientID, txtEndDate.ClientID);
and from the method you can access it like shown below
function DateValidation(txtStartDate, txtEndDate) {
debugger;
var stdate = Date.parse(txtStartDate.value);
I think the problem is that you're not comparing dates - you have just declared them as vars without a type so they're essentially Strings.
Check out the Date.parse() method.
Adding to what the previous 2 guys have answered with, you have to parse the dates. You also need to validate that they are even dates. I use this library often when working with dates on the client side:
http://www.datejs.com/
The main problem is how you register the event. You are creating a string with code that contains string literals with the values, which means that you get the values from the textboxes at the time that you create the string, not at the time that the event is activated. You have to make a postback before the code is updated with the current values, that is why it doesn't work on the first click.
Create code that gets the values at the time of the click:
btnShowReport.Attributes.Add("onclick", "return DateValidation(document.getElementById('" + txtStartDate.ClientID + "').value, document.getElementById('" + txtEndDate.ClientID + "').value);");
Another possible problem is that the code doesn't compare dates, it compares strings. Some date formats are comparable as strings, e.g. ISO 8601 based formats: "2010-12-31" < "2011-01-01", but other date formats has to be parsed into dates to be compared, e.g. "31/12/2010" > "01/01/2011".
Parse the dates after checking that they are not empty:
...
if (startDate != '' && EndDate != '') {
var stdate = Date.parse(startDate);
var enddate = Date.parse(EndDate);
...

How do I write a loop that prints this kind of text regarding date differences?

I need to generate a code where i will be getting an user input (an int) and using that i need to generate days of the week
example: user inputs - 5
I need to output something like below
Today is (todays date)
Tomorrow is (tomorrows date)
Day after tomorrow is
two days after tomorrow is
three days after tomorrow is ...
and if the user enters 6 it should output 6days as above.
please help as i'm an novice in C#
Thanks alot
I won't write code for you. Would like to give some hints.
You can use DateTime class to find out the current date and time and it also provide methods which you can easily use to find what next day is and similar.
You can use While Loop as you said in Title or even For can work
You can take input from user through Console class if you are making console based app otherwise you can take input in some textbox.
For loop or while loop will run for current day plus number that user have entered minus 1
static void Main(string[] args)
{
days();
}
public static void days()
{
Console.Write("Please enter number : ");
int a = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < a; i++)
{
string strdays;
switch (i)
{
case 0:
strdays = ". Todays date is : ";
break;
case 1:
strdays = ". Tommorrows date is : ";
break;
case 2:
strdays = ". Day after tommorrows date is : ";
break;
default:
strdays = ". " + (i-1) + "Days after tommorrows date is : ";
break;
}
Console.WriteLine((i+1)+ strdays + System.DateTime.Now.AddDays(i));
}
Console.ReadLine();
}
hope this help u..
The pieces of code you will need:
Console.Write
Console.ReadLine
int.Parse (to convert the input to an integer)
DateTime.Today
DateTime.AddDays(zeroOrMoreDays)
DateTime.DayOfWeek (if you want Wednesday instead of 10/19/2011 12:00:00 AM)
Here is some pseudo-code:
Ask the user for the number of days (as a string)
Parse numberOfDays into an int
for i = 0 to numberOfDays:
write line: today.AddDays(i).DayOfWeek
You'll also need to do some tricks to get the natural language stuff to work, e.g. three days after tomorrow is.
I'd use a few extra if i == 0 else if i == 1 type statements to solve this, and fall back on a general <number> days after tomorrow after a certain point.
See this (closed) question for links on how to get that number: converting numbers in to words C#
Edit due to your comments on the question
# sblom ... nope for a web service i'm planning
Don't use Console stuff then.
Make this a method instead, and don't do the string/int.Parse stuff. Just take an int directly.
Build a result with a StringBuilder, and return a string, rather than printing out the result directly.
int diff=0;
while (diff < 5)
{
Console.WriteLine(DateTime.Now.AddDays(diff));
diff++;
}
Int32 numberOfDays = 5;
DateTime dt = DateTime.Now;
for (int i = 0; i < numberOfDays ; i++)
{
Console.WriteLine(dt.AddDays(i).DayOfWeek);
}
Hope it helps! =)
// num is number if days we'll loop through
int num = 5;
// gets the current date time - save it off. even though incrementing days, in other
// date incrementing functions (min, sec etc...) it's important to save off
DateTime now = DateTime.Now;
// init a countervar
int count = 0;
// loop until num times
while (count < num)
{
// add the current count number of days and print
// ++ after the variable increments it after calculating the new date
DateTime curr = now.AddDays(count++);
// output the value - it ends up calling .ToString() on date.
Console.WriteLine(curr);
}

Categories