Add day to dateTime [duplicate] - c#

This question already has answers here:
Why DateTime.AddHours doesn't seem to work?
(8 answers)
Closed 6 years ago.
I have dateTime variable and I would like to add one day if date is not the last day of month, but one day before the last.
endDate = newDate(2016, 8, 30);//create date for test
if (DateTime.DaysInMonth(endDate.Year, endDate.Month) == (int)31 && endDate.Day == (int)30)
endDate.AddDays(1);
From debugger I can see that execution goes on endDate.AddDays(1); but endDate is still the same (30.08.2016) as if AddDays function doesn't work.
Anybody knows why?

AddDays does not change the date but returns a new date with the added days. So for endDate to change you must assign the output of the function to it:
var endDate = new DateTime(2016, 8, 30);
endDate = endDate.AddDays(1);

It returns a result that you have to assign as a DateTime is a struct and is immutable. Also if you checked out the documentation you will see that the method returns a DateTime instance.
endDate = endDate.AddDays(1);
About your logic, you want to increment it by 1 date if its the day before the last day of the month. What you have now is wrong and could be better written like this:
// only increment if one day before last day of month
if ((DateTime.DaysInMonth(endDate.Year, endDate.Month) - 1) == endDate.Day)
endDate = endDate.AddDays(1); // assign the returned value
Take the result from the last day and subtract 1 to get the day before the last day of the month. If that is equal to your date's current day of the month then increment by one.

Not all months have 31 days.
Here's the updated piece of code:
var endDate = new DateTime(2017, 2, 27);//create date for test
var daysInMonth = DateTime.DaysInMonth(endDate.Year, endDate.Month);
if(endDate.Day == daysInMonth - 1)
endDate = endDate.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.

What condition should we write to get gaps between dates at least 28 days?

I am writing a code in which I have taken start date and end date as input.(and want to show date between these range) Now I want to make sure that the gap between these two dates should be greater than 28 days i.e. 4 week. If user giving two dates having gap of 5 days then the start date should be change accordingly.
I tried some if else conditions but not getting the desired result.
***
if(enddate == DateTime.Now.Date){ startdate = ed.AddDays(-28);}
else if(enddate < )
else if()
else
***
What should be the other conditions?
Something like:
var startdate = DateTime.Now;
var enddate = DateTime.Now.AddDays(5);
if((enddate-startdate).Days<28)
{
startdate = enddate.AddDays(-28);
}
After if statement the gap between startdate and enddate will be at least 28 days

Round up DateTime

For my SteamBot I want to store the date and the time when the item is tradable again.
Example:
// DateNow = 05.06.2019 13:37:00
(+ 7 days due to Steam's trade policy)
// DateNow+7Days = 12.06.2019 13:37:00
// DateIneed = 13.06.2019 09:00:00
So the DateTime I need is CurrentDateTime + 7 Days + The rest to 9 o'clock
This is how far I come:
var date = DateTime.Now.AddDays(7);
Is there any smart way to always get the DateTime I need?
Language is C#
You can check if it is before 9 o'clock today, then set the time to 9, else add one day and set the time to 9, should be fairly easy I think.
var time = DateTime.Now;
var date = time.Hour <= 9
? time.Date.AddDays(7).AddHours(9)
: time.Date.AddDays(7).AddHours(9).AddDays(1);
The DateTime.Date field exposes just the date of a DateTime, you can then add an arbitrary TimeSpan to that to set the time of a DateTime object to whatever you want;
DateTime.Now.AddDays(7).Date.Add(new TimeSpan(9, 0, 0))
Check it out in action here: https://dotnetfiddle.net/l3X37y
Given the hour of the day may be past 9AM already, it's possible to end up with a DateTime less than 7 days, to counter this you can check if the hour of the day exceeds what you're going to set the DateTime to and add a day if it does, like so;
DateTime dt = DateTime.Now.AddDays(7);
dt = dt.Date.Add(new TimeSpan(dt.Hour >= 9 ? 1 : 0, 9, 0, 0))
See this one in action here: https://dotnetfiddle.net/lfVGis

Retrieve date of the prior Tuesday [duplicate]

This question already has answers here:
Compute the DateTime of an upcoming weekday
(11 answers)
Closed 9 years ago.
I need to retrieve the date, month, and year of the last Tuesday relative to any given date. For example, today is Friday, 1st March 2013. I want my method to return the date of the prior Tuesday: 26th February, 2013. How can I achieve this?
This should do the trick.
var yesterday = DateTime.Now;
while(yesterday.DayOfWeek != DayOfWeek.Tuesday) {
yesterday = yesterday.AddDays(-1);
}
I'd do something like this:
var lastTuesday = DateTime.Today.AddDays(
-1 * (DateTime.Today.DayOfWeek - DayOfWeek.Tuesday));
var lastMonday = DateTime.Today.AddDays(
-1 * (DateTime.Today.DayOfWeek - DayOfWeek.Monday));
This was essentially answered here: Get date of first Monday of the week?
DateTime input = DateTime.Now;
int delta = DayOfWeek.Tuesday - input.DayOfWeek;
DateTime tuesday = input.AddDays(delta);

C# Add TimeSpan to DateTime by considering BusinessDays

I have a collection of dates that are business days and I have a Start Date. When I add a TimeSpan to the Start Date DateTime I have to ensure that when adding the days in TimeSpan, I skip over holidays. Any suggestions on how I can do this?
You add the timespan as it is. When that is done, you iterate search for dates in your collection that falls between the original date and the new date. For each time you encounter for each hit you add another day to the new date, and repeat until you are through your collection of dates. This can be optimized if your datecollection is sorted.
You need to take into account how many non-business days there are in any added date range.
In a 20 day range, there may be 6 non-business days.
You can't just add this number of days to the last day because the new date range may contain non-business days too. You have to add the days, and then figure out how many of those days you've added are also holidays:
Here's some non-tested pcode
Add Timespan to date (DateIn,timespan)
finalDateTime = (fromDate + timespan)
fromDate = DateIn.date
toDate = finalDateTime.date
repeat
iDays = GetHolidaysBetween (fromDate, toDate)
finalDateTime = (finalDateTime + iDays)
fromDate = (toDate+1)
toDate = (toDate+iDays)
until (iDays=0)
return finalDateTime
end_function
What about something like this?
public DateTime AddBusinessDays(List<DateTime> businessDays, DateTime startDate, TimeSpan span)
{
// Add the initial timespan
DateTime endDate = startDate.Add(span);
// Calculate the number of holidays by taking off the number of business days during the period
int noOfHolidays = span.Days - businessDays.Where(d => d >= startDate && d <= endDate).Count();
// Add the no. of holidays found
endDate.AddDays(noOfHolidays);
// Skip the end date if it lands on a holiday
while (businessDays.Contains(endDate))
endDate = endDate.AddDays(1);
return endDate;
}

Categories

Resources