Date is not incrementing in WHILE or FOR loop - c#

What's wrong with the following code? The date is not incrementing in my FOR loop so it goes into an endless loop because the condition is never met. I also tried it with a WHILE loop and got the same result.
var startDate = DateTime.Today;
var endDate = new DateTime(2016, 12, 31);
for (var date = startDate; date <= endDate; date.AddDays(1))
{
// Some logic here
}

AddDays doesn't modifies value of date, it just returns new instance of DateTime, and you're not assigning back incremented value.
It should be
for (var date = startDate; date <= endDate; date = date.AddDays(1))

From the documentation:
Returns a new DateTime that adds the specified number of days to the
value of this instance.
So, date.AddDays(1) doesn't change the value of date; it returns a new DateTime representing the changed value. If you want to change date, do this:
date = date.AddDays(1);

Related

How do I handle datetime with no day in a linq comparison?

I am given two dates as strings like this:
Beginning month: 10
Beginning year: 2010
Ending month: 01
Ending Year 2020
I want to query my entity and get everything that is equal or between these ranges.
So, I want everything from 10/2010 to 01/2020.
I have this code and I got stuck on how to convert the date correctly and the comparison:
dollartotals = (from x in se.AchBatches
where x.CompanyCode == company &&
DbFunctions.TruncateTime(x.DateTimeSubmitted) >=
// stuck here
select x.DollarTotal).Sum();
How do I handle the individual month/year strings and make a date comparison without a day?
Thanks for any assistance!
You want to check against the actual datetime submitted, not a truncated version of it.
The key is to build actual datetimes in advance, then just do a regular date window check.
Assume you have four strings as listed in your question:
//you might use TryConvert or a Try block here to validate your string data...
int beginYear = Integer.Convert(strBeginYear);
int beginMonth = Integer.Convert(strBeginMonth);
int endYear = Integer.Convert(strEndYear);
int endMonth = Integer.Convert(strEndMonth);
DateTime start = new DateTime(beginYear, beginMonth, 1);
DateTime endLimit = new DateTime(endYear, endMonth, 1).AddMonths(1);
dollartotals = (from x in se.AchBatches
where x.CompanyCode == company &&
x.DateTimeSubmitted >= start &&
x.DateTimeSubmitted < endLimit
select x.DollarTotal).Sum();
I want everything from 10/2010 to 01/2020.
Not sure if you want a DateTime sequence with every Tick between those dates, or every second, or every Day. Let's assume you want every Day: All Days from startDate.Date until and inclusive endDate.Date.
I use StartDate.Date, so if StartDate is 2020-02-05 13:20:14, then you still get February 5th 2020 at 00:00:00
IEnumerable<DateTime> GetDateRange(DateTime startDate, DateTime endDate)
{
DateTime lastDate = endDate.Date;
DateTime date = startDate.Date;
while (date <= lastDate)
{
yield return date;
date = date.AddDays(+1);
}
}
Usage:
var allDaysOfFebruary2020 = GetDateRange(new DateTime(2020, 01, 01),
new DateTime(2020, 02, 29));
You'll get the sequence from 1st February 2020 until and inclusive 29th February 2020.

Date range is not working properly in for loop

I am using a for loop with date range in C#.
for (var date = fromDate;date <= toDate; date.Value.AddMonths(1))
However, I found out that the date value is not added in the looping. Is that the AddMonths is not appropriate in the for loop? How should I add the months in the for loop?
DateTime values in c# are immutable. That is, after they are created, they can't be changed.
What you can do, is assign a new value to the date variable.
for (var date = fromDate.Value; date <= toDate; date = date.AddMonths(1))
{
// do something with date
}

Remove hours:minutes:seconds from System.DateTime.Now

I want to insert just year : month : day for a specific column in a database table row, but my variable is of DateTime Type.
To remove milliseconds I just used following code:
DateTime createdate = System.DateTime.Now;
createdate = createdate.AddTicks(-(createdate.Ticks % TimeSpan.TicksPerSecond));
How to remove hours, minutes, seconds from this?
You can use .Date property which set's the time part to midnight.
DateTime justDate = createdate.Date;
or you can use DateTime.Today which generates the same result for DateTime.Now.Date value.
DateTime justDate = DateTime.Today;
If you use SQL Server, date type is mapped with DateTime on CLR side which you can safely insert that value.
Use the Date property on your createdate variable to return just the date component without the time component.
DateTime createdate = System.DateTime.Now;
createdate = createdate.AddTicks(-(createdate.Ticks % TimeSpan.TicksPerSecond));
var dateOnly = createdate.Date;
Note you will still have the time in the object, set to 00:00:00

Not able to add days to a date in a loop more than once

I have this code on selected index changed of a dropdownlist which represents months.
DateTime firstDate, lastDate;
int mon = DropDownList1.SelectedIndex +1;
int year = 2013;
GetDates(mon, year,out firstDate , out lastDate);
DateTime f = firstDate;
DateTime d2 = firstDate.AddDays(7);
for (;d2.Month == mon; )
{
d2.AddDays(7); // value after first iteration is "08-Apr-13 12:00:00 AM"
// but beyond first iteration the value remains the same.
}
private void GetDates(int mon, int year, out DateTime firstDate, out DateTime lastDate)
{
int noOfdays = DateTime.DaysInMonth(year, mon);
firstDate = new DateTime(year, mon, 1);
lastDate = new DateTime(year, mon, noOfdays);
}
I was hoping that d2 will keep getting incremented by 7 days in each iteration as long as resulting value is in the same month. But it seems that the value increments just once. i.e from 01-Apr-13 12:00:00 AM to 08-Apr-13 12:00:00 AM
You have to assign changed date object back to date object d2 because DateTime object is immutable. AddDays method returns new object instead of changing the object on which it is called so you have to assign it back to calling object.
d2 = d2.AddDays(7);
Edit Why it works for first iteration ?
Because you are intializing the date object by add 7 days before loop.
DateTime d2 = firstDate.AddDays(7);
Shouldn't it be?
d2 = d2.AddDays(7);

Comparing just dates from DateTime C#

My table contains 2 fields with values,
StartTime EndTime
3/6/2010 8:00:00 AM 3/6/2010 10:20:00 AM
Now I have a datepicker control wherein the user can select a date,
C# Logic:
DateTime SelDate;
if (datePicker.SelectedDate == null)
SelDate = DateTime.Now;
else
SelDate = datePicker.SelectedDate;
I am trying to compare dates by the below code but it gives me compile time error,
foreach (DomainObject obj in res.ResultSet)
{
MyClass adef = (MyClass)obj;
DateTime sTime = (DateTime)adef.StartTime;
DateTime eTime = (DateTime)adef.EndTime;
if ((SelDate.ToShortDateString >= sTime.ToShortDateString) && (SelDate.ToShortDateString <= eTime.ToShortDateString))
{
actdef.Add(new MyClassViewModel(adef));
}
}
I just want to take the date for comparison and not the time part. So I have used the ToShortDateString method.
Just use the Date property of DateTime:
if (SelDate.Date >= sTime.Date)
Also note that you can use DateTime.Today to get the start of today.
Just use the Date property of the DateTime and do a straight comparison.
DateTime SelDate = datePicker.SelectedDate == null ? DateTime.Now : datePicker.SelectedDate;
if( SelDate.Date >= sTime.Date )
{
// do something here
}

Categories

Resources