How to Compare two date without timeline in C# - c#

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

Related

Find Date Overlapping in DataTable Using Linq C# [duplicate]

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

Comparing the values of 2 combo-boxes

I have two combo box, one with a start date, and the other is ending date.
I want to do if(combobox1 > combobox2) check if the start date is greater than the ending date MessageBox.Show("You have chosen a great starting date of the final");
How can this be done?
Just access both values of your ComboBoxes and then you can use DateTime.Compare method:
https://msdn.microsoft.com/en-us/library/system.datetime.compare(v=vs.110).aspx
This might fix the issue
var StartDate = comboBoxDate1.Text;
var EndDate = comboBoxDate2.Text;
var eDate = Convert.ToDateTime(EndDate);
var sDate = Convert.ToDateTime(StartDate);
if(StartDate != "" && StartDate != "" && sDate > eDate)
{
Console.WriteLine("Please ensure that the End Date is greater than the Start Date.");
}
It depends what you have under your ComboBoxes.
If you have just texts:
var dateFrom = Convert.ToDateTime(ComboBox1.Text);
var dateTo = Convert.ToDateTime(ComboBox2.Text);
if(dateFrom > dateTo)
{
// your code
}
If you have bound objects where ValueMember is of Type DateTime
var dateFrom = (DateTime)ComboBox1.SelectedValue;
var dateTo = (DateTime)ComboBox2.SelectedValue;
if(dateFrom > dateTo)
{
// your code
}
DateTime date1 = Convert.ToDateTime(comboBox1.Text);
DateTime date2 = Convert.ToDateTime(comboBox2.Text);
if(date1>date2)
{
MessageBox.Show("You have chosen a great starting date of the final");
}
Simple as this :
DateTime d1 = Convert.ToDateTime(ComboBox1.SelectedValue.toString());
DateTime d2 = Convert.ToDateTime(ComboBox2.SelectedValue.toString());
if(d1 > d2)
{
MessageBox.Show("Some message");
}

C# DateTime to Int and RadCalendar

I am trying to parse out a RadCalendar Date and disable the dates prior to our Start Date of an event.
We get our StartDateTime from a database and I would like to disable the dates from our Future StartDateTime all the way back to the beginning of the current (this) month.
EDIT: More specific
Example: My StartDateTime is in November 2014 but I want to disable all dates from that future date until back to the beginning of this current month (this month is August 2014).
Below is the code we currently have, but it is only looking back i < 31. This is why I would like to the DateTime get the number of days as an int all the way back to the beginning (the 1st) of the current month.
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime dt = nextAvailableTime.StartDateTime.AddDays(-1);
for (var i = 0; i < 31; i++) //Would like to change this to beginning of current month.
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = dt.Date.AddDays(i * -1), IsDisabled = true, IsSelectable = false });
}
}
Why not subtract the 2 dates and get the difference in days? I used my own variable because I was unclear what your variables were. My loop is disabling going forward instead of multiplying by -1. You may need to edit the loop to be <= or start from 1 depending on if you want the first and last date to be included.
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime currentDate = DateTime.Now;
DateTime futureDate = DateTime.Now.AddMonths(3);
int daysBetween = (futureDate - currentDate).Days;
for (var i = 0; i < daysBetween; i++)
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = currentDate.AddDays(i), IsDisabled = true, IsSelectable = false });
}
}
The answer we came up with was to get the next available date and then the beginning date of the current month and get the difference using DayOfYear.
Solution is below:
if (nextAvailableTime != null && nextAvailableTime.StartDateTime > DateTime.Today)
{
//DISABLE dates prior to next available date
DateTime dt = nextAvailableTime.StartDateTime.AddDays(-1);
DateTime nextDate = nextAvailableTime.StartDateTime;
//Gate the calendar to just go get the product's next available date and then get block out everything until the beginning of the current month.
var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
TimeSpan daysBetween = (futureDate - startOfMonth);
// for (var i = 0; i < 31; i++)//Original from 31 days from next available.
for (var i = 0; i < daysBetween.Days; i++) //Get difference between next available and beginning of current month.
{
tkCalendar.SpecialDays.Add(new RadCalendarDay(tkCalendar) { Date = dt.Date.AddDays(i * -1), IsDisabled = true, IsSelectable = false });
}
}

How to determine if a date it was yesterday, in the last month, in the last year using c#?

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

What is the best way to findout whether a date falls in particular range?

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.

Categories