I have a WebApplication that manages events into tables like an Agenda..
For each event I have a StartDate and EndDate.
In the Application I want to export the events into a graph, and I want to check if the event passes the range of the required dates.
For example:
Event 1: StartDate (9 September) EndDate (14 September)
I want to check if it passes (10 Sept - 16 Sept)
This is a photo of the events example Graph:
This is a code that checks for only one date:
public static bool Within(this DateTime current, DateTime startTime, DateTime endTime)
{
return startTime < currentTime < endTime;
}
Edit:
To clarify more, I want the function to return true if the event passes the 2 dates range,
even if it start before the range or ends after the rang it should return true anyway.
only return false if it does not pass the range.
public static bool Within(DateTime one, DateTime two,
DateTime lowBound, DateTime highBound)
{
return one >= lowBound && two <= highBound;
}
public static bool Within(this DateTime current, DateTime startTime, DateTime endTime)
{
return startTime < currentTime && currentTime < endTime;
}
And call it twice
lowDate.Within(eventStart, eventEnd) && heDate.Within(eventStart, eventEnd)
Got the answer this way:
public static bool Within(DateTime StartDate, DateTime EndDate, DateTime StartRange, DateTime EndRange)
{
if ((StartDate == EndDate) && (StartRange <= StartDate && StartDate <= EndRange))
return true;
else
return ((StartRange >= StartDate && StartRange <= EndDate) || (EndRange >= StartDate && EndRange <= EndDate));
}
Related
This question already has answers here:
Linq Overlapped date range checking in single collection
(2 answers)
Closed 1 year ago.
I have a datatable having startdate and enddate columns. I want to check overlapping startdate and enddate using linq.
method input Parameters:
Input DataTable
startDate
endDate
01/Jan/2021
31/Jan/2021
01/Feb/2021
28/Feb/2021
Input Parameters
FromDate: 15/Feb/2021
ToDate: 20/Feb/2021
Expected OutPut: true
I have created a function to check for overlapping dates.
private bool IsDateOverlap(DateTime? FromDate, DateTime? ToDate, DataTable Table)
{
bool isOverlap = false;
try
{
for (int index = 0; index < Table.Rows.Count; index++)
{
if (index == this.RowID)
continue;
DateTime? rowFromDate = Convert.ToDateTime(Table.Rows[index]["startDate"]);
DateTime? rowToDate = Convert.ToDateTime(Table.Rows[index]["endDate"]);
isOverlap = (FromDate <= rowToDate && rowFromDate <= ToDate);
if (isOverlap)
break;
}
}
catch (Exception ex)
{ }
return isOverlap;
}
Its working fine.
I want to do it using linq. Thanks in Advance.
I have an approach that might help you how ever i use a custom object rather than a datatable.
public static List<inputDataTable> ListOfDates = new List<inputDataTable>
{
new inputDataTable { startDate = DateTime.Parse("01/Jan/2021"), endDate = DateTime.Parse("31/Jan/2021"),},
new inputDataTable { startDate = DateTime.Parse("01/Feb/2021"), endDate = DateTime.Parse("28/Feb/2021"),},
};
public static bool checkOverlapping(DateTime starDate, DateTime endDate, List<inputDataTable> storeDate)
{
var e = storeDate.Where(a=> (starDate >= a.startDate && starDate <= a.endDate) || (endDate >= a.startDate && starDate <= a.endDate) );
if(e.Count() > 0)
{
return true;
}
else
{
return false;
}
}
Also you can visit these threads;
Check dates fall within range using Linq
Check One Date is falling Between Date Range-Linq query
How to calculate actual working days of my when user checkin in hotel? I want to count working days only except Saturday and Sunday. Please check below function its count working days but in parameter I entered startdate and enddate.
I want send only startdate its automatically count 15 working days and return me enddate.
//Days count
public static double GetBusinessDays(DateTime startD, DateTime endD)
{
double calcBusinessDays =
1 + ((endD - startD).TotalDays * 5 -
(startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
if (endD.DayOfWeek == DayOfWeek.Saturday) calcBusinessDays--;
if (startD.DayOfWeek == DayOfWeek.Sunday) calcBusinessDays--;
return calcBusinessDays;
}
I want like this:
public static Datetime GetBusinessDays(DateTime startDate)
{
Datetime After15WorkingDaysDate;
return After15WorkingDaysDate;
}
Here are two methods.
The idea is to generate each date in the range, decide whether it is a Business Day, and only then add it to the result list.
GetBusinessDaysInRange returns a list of the dates of the Business Days between the given start and end date. End date is exclusive, i.e. if the end date is a Business Day, it will not be part of the result.
// Returns a list of the dates of the Business Days between the given start and end date
public static IEnumerable<DateTime> GetBusinessDaysInRange(DateTime startDate, DateTime endDate, DayOfWeek[] closedOn) {
if (endDate < startDate) {
throw new ArgumentException("endDate must be before startDate");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (date < endDate) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
GetFixedNumberOfBusinessDays returns a list of the dates of the Business Days from the given start with the given number of days (the method you asked for).
// Returns a list of the dates of the Business Days from the given start with the given number of days
public static IEnumerable<DateTime> GetFixedNumberOfBusinessDays(DateTime startDate, int numberOfBusinessDays, DayOfWeek[] closedOn) {
if (numberOfBusinessDays < 0) {
throw new ArgumentException("numberOfBusinessDays must be zero or positive.");
}
var businessDays = new List<DateTime>();
var date = startDate;
while (businessDays.Count() < numberOfBusinessDays) {
if (!closedOn.Contains(date.DayOfWeek)) {
businessDays.Add(date);
}
date = date.AddDays(1);
}
return businessDays;
}
The parameter DayOfWeek[] closedOn was introduced because you do not want to hardcode the days of the week that are not Business Days.
The return type was changed to IEnumerable<DateTime> so this method is more universal. If you only want the number of days and are not interested in the actual dates, just run a .Count() on the result. If you want the end date, call .Last().
.Net Fiddle with usage examples:
var closedOn = new DayOfWeek[] { DayOfWeek.Saturday, DayOfWeek.Sunday };
var start = new DateTime(2018, 07, 23);
var numberOfDays = 10;
var businessDays = GetFixedNumberOfBusinessDays(end, numberOfDays, closedOn);
int actualNumberOfBusinessDays = businessDays.Count(); // 10
DateTime endDate = businessDays.Last(); // Friday, August 3, 2018
It should be generic method. You can add different work day in another place.
public static DateTime AddWorkdays(this DateTime originalDate, int workDays)
{
DateTime tmpDate = originalDate;
while (workDays > 0)
{
tmpDate = tmpDate.AddDays(1);
if (tmpDate.DayOfWeek == DayOfWeek.Saturday ||
tmpDate.DayOfWeek == DayOfWeek.Sunday )
workDays--;
}
return tmpDate;
}
DateTime endDate = startDate.AddWorkdays(15);
I would like to determine if a DateTime was yesterday, if it was in the last month and if it was in the last year.
For example if today is 2013. 10. 21. then 2013. 10. 20. was yesterday, 2013. 09. 23. was in the last month and 2012. 03. 25. was in the last year.
How can i determine these using c#?
// myDate = 2012.02.14 ToDate ... you know
if (myDate == DateTime.Today.AddDays(-1);)
Console.WriteLine("Yestoday");
else if (myDate > DateTime.Today.AddMonth(-1) && myDate < DateTime.Today)
Console.WriteLine("Last month");
// and so on
it needs test and fixes, but it is the way ;)
bool IsYesterday(DateTime dt)
{
DateTime yesterday = DateTime.Today.AddDays(-1);
if (dt >= yesterday && dt < DateTime.Today)
return true;
return false;
}
bool IsInLastMonth(DateTime dt)
{
DateTime lastMonth = DateTime.Today.AddMonths(-1);
return dt.Month == lastMonth.Month && dt.Year == lastMonth.Year;
}
bool IsInLastYear(DateTime dt)
{
return dt.Year == DateTime.Now.Year - 1;
}
I think testing like this could do the trick:
if(new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(-1) > dateToTestIfLastMonth){
http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx
You can subtract dates then check the timespan object.
Straightforward implementation:
public enum DateReference {
Unknown,
Yesterday,
LastMonth,
LastYear,
}
public static DateReference GetDateReference(DateTime dateTime) {
var date = dateTime.Date;
var dateNow = DateTime.Today;
bool isLastYear = date.Year == dateNow.Year - 1;
bool isThisYear = date.Year == dateNow.Year;
bool isLastMonth = date.Month == dateNow.Month - 1;
bool isThisMonth = date.Month == dateNow.Month;
bool isLastDay = date.Day == dateNow.Day - 1;
if (isLastYear)
return DateReference.LastYear;
else if (isThisYear && isLastMonth)
return DateReference.LastMonth;
else if (isThisYear && isThisMonth && isLastDay)
return DateReference.Yesterday;
return DateReference.Unknown;
}
I want to compare two dates. In pseudo-code:
If the dueDate > now or dueDate = now
Then Fine Amount = something.
Else Fine Amount = 0
I wrote below code:
DateTime dueDate = Convert.ToDateTime(Reader1[3].ToString());
DateTime now = DateTime.Now;
int result = DateTime.Compare(dueDate, now);
if ((result < 0) || (result == 1))
{
row["Fine_Amount"] = Convert.ToDouble(Reader1[4].ToString());
}
else
{
row["Fine_Amount"] = 0;
}
This code gives wrong value, when
dueDate = 23-12-2011 AM 12:00:00
now = 23-12-2011 PM 05:26:54
I want to Compare:
dueDate = 23-12-2011
now = 23-12-2011
How do I remove the time in that?.
Adding below code is given result. But its to lengthy code.: -
DateTime dueDate = Convert.ToDateTime(Reader1[3].ToString());
DateTime now = DateTime.Now;
if (dueDate.Year < now.Year)
{
row["Fine_Amount"] = Convert.ToDouble(Reader1[4].ToString());
}
else if (dueDate.Year > now.Year)
{
row["Fine_Amount"] = 0;
}
else if (dueDate.Year == now.Year)
{
if (dueDate.Month < now.Month)
{
row["Fine_Amount"] = Convert.ToDouble(Reader1[4].ToString();
}
else if(dueDate.Month > now.Month)
{
row["Fine_Amount"] = 0;
}
else if(dueDate.Month == now.Month)
{
if(dueDate.Day < now.Day)
{
row["Fine_Amount"] = Convert.ToDouble(Reader1[4].ToString();
}
else
{
row["Fine_Amount"] = 0;
}
}
}
Is there any way to short this code?.
Answer For this Question is
if (dueDate.Date >= now.Date)
{
row["Fine_Amount"] = 0;
}
else
{
row["Fine_Amount"] = Convert.ToDouble(Reader1[4].ToString());
}
This datetime.date is gives
dueDate = 23-12-2011 AM 12:00:00 to 23-12-2011 AM 12:00:00
now = 23-12-2011 PM 05:26:54 to 23-12-2011 AM 12:00:00
You can use DateTime.Now.Date
According to docs, Date property returns: A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00).
The DateTime class in C# supports comparison by simply using <, >, and == operators. Do it like your above written pseudo code.
dueDate.Date >= DateTime.Now.Date
Although you could use the .Date property of DateTime it is generally a good practice to compare a certain date to a date range:
startDate <= someDate && someDate < endDate
You can use the DateTime.Date Property to gets the date component of a DateTime value:
if (dueDate.Date >= DateTime.Now.Date)
use the Date property of DateTime object for comparison
I tried the following
DateTime start = Convert.ToDateTime(TextBox1.Text);
DateTime end = Convert.ToDateTime(TextBox2.Text);
if (DateTime.Now.Date == start.Date || DateTime.Now.Date == end.Date || (DateTime.Now >= start.Date && DateTime.Now <= end.Date))
{
lblResult.Text = "true";
}
else
{
lblResult.Text = "false";
}
This verifies if the date range is one day also. Any way to reduce the number of conditions above?
DateTime start = Convert.ToDateTime(TextBox1.Text);
DateTime end = Convert.ToDateTime(TextBox2.Text);
DateTime now = DateTime.Now;
if (now >= start.Date && now <= end.Date)
{
lblResult.Text = "true";
}
else
{
lblResult.Text = "false";
}
Only the last codition is needed, and you can take the Date part of the DateTime on converting. Use the Date part of Now, otherwise if the "start" and "end" strings are the same - the condition returns false (because when taking only the Date part of a DateTime, the time is represented as 00:00:00...)
DateTime start = Convert.ToDateTime(TextBox1.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(TextBox2.Text).Date;
if (now >= start && now <= end)
{
lblResult.Text = "true";
}
else
{
lblResult.Text = "false";
}
If you want to verify that the range contains only one day, just remove the "smaller than"/"greater than" conditionings:
(now = start && now = end)
thus making sure that "now" is the same date as "start" and "end", but this isn't really a "falls within range" check.
DateTime dateStart = Convert.ToDateTime(TextBox1.Text);
DateTime dateEnd = Convert.ToDateTime(TextBox2.Text);
if (DateTime.Now.Date == dateStart .Date || DateTime.Now.Date == dateEnd .Date || (DateTime.Now >= dateStart .Date && DateTime.Now <= dateEnd .Date))
{
lblResult.Text = "true";
}
else
{
lblResult.Text = "false";
}
In my opinion you can leave out those 2 checks:
DateTime.Now.Date == dateStart .Date || DateTime.Now.Date == dateEnd .Date
since
DateTime.Now >= dateStart .Date && DateTime.Now <= dateEnd .Date
is also checking wheter your startdate falls on today's date.
<= means smaller or the same.