Comparing the values of 2 combo-boxes - c#

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

Related

Calculation did not perform to calculate the difference in total days between 2 dates in c#asp.net sql linq

DateTime currentDate = DateTime.Now;
var query = (from m in db.Users where m.EmailAddress == emailAddress select m.Last_Login_Date).Single();
DateTime lastLoginDate = Convert.ToDateTime(query);
double diffDays = (currentDate - lastLoginDate).TotalDays;
if (diffDays < 72) {
Security.LoginUser(u.Name, u.Role, rememberMe);
u.Last_Login_Date = currentDate;
} else {
Response.Redirect("ResetPwd.aspx");
}
I tried to perform the calculation to find the difference in total days. So if the difference is >72 days, they will be forced to do the Resetting password. But now the formula can't be performed. I think that my code have some errors. so currentDate and the db.Users Last_Login_Date are in DateTime type. Anyone has any ideas how to do the calculation, or should I change my UserDB Last_Login_Date to string type?
Please try following:
//DateTime.Subtract() method will return a 'TimeSpan' value.
var timeSpan = currentDate.Subtract(lastLoginDate);
var diffDays = timeSpan.Days;
if(diffDays < 72)
{
//Code here.
}
Working solution is in the below link:
dotnetfiddle
So, I found a solution to my question. I changed to TimeSpan and it all worked now.Thanks for giving contribution.
DateTime currentDate = DateTime.Now;
var query = (from m in db.Users
where m.EmailAddress == emailAddress
select m.Last_Login_Date).Single();
DateTime lastLoginDate = Convert.ToDateTime(query);
TimeSpan diffDays = currentDate.Subtract(lastLoginDate);
if (diffDays.TotalDays> 72)
{
Response.Redirect("ResetPwd.aspx");
}
else
{
Security.LoginUser(u.Name, u.Role, rememberMe);
u.Last_Login_Date = currentDate;
}

How to count working 15 days and get enddate?

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

Need Function to Get First day and last day of current week

I have two labels First day and Last day in which I want to update it on button click.
I need Function to Get First day and last day of current date so that I can display it on click of next and previous button.
Here is what I have so far:
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
DayOfWeek firstDay = cultureInfo.DateTimeFormat.FirstDayOfWeek;
firstDayInWeek = dayInWeek.Date;
lastDayInWeek = dayInWeek.Date;
while (firstDayInWeek.DayOfWeek != firstDay)
firstDayInWeek = firstDayInWeek.AddDays(-1);
but does not give me the next week after this month.
This is what exactly i'm looking for :
Any one can help to make this working using a single function.
DateTime baseDate = DateTime.Now;
var thisWeekStart = baseDate.AddDays(-(int)baseDate.DayOfWeek);
var thisWeekEnd = thisWeekStart.AddDays(7).AddSeconds(-1);
Try this :
private static void GetWeek(DateTime now, CultureInfo cultureInfo, out DateTime begining, out DateTime end)
{
if (now == null)
throw new ArgumentNullException("now");
if (cultureInfo == null)
throw new ArgumentNullException("cultureInfo");
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
int offset = firstDayOfWeek - now.DayOfWeek;
if (offset != 1)
{
DateTime weekStart = now.AddDays(offset);
DateTime endOfWeek = weekStart.AddDays(6);
begining = weekStart;
end = endOfWeek;
}
else
{
begining = now.AddDays(-6);
end = now;
}
}
Usage example:
DateTime begining;
DateTime end;
var testDate = new DateTime(2012, 10, 10);
GetWeek(testDate, new CultureInfo("fr-FR"), out begining, out end);
Console.WriteLine("Week {0} - {1}",
begining.ToShortDateString(),
end.ToShortDateString()); // will output Week 10/8/2012 - 10/14/2012
So, on a button click, you have a one week period. Lets say that is defined by a starting date. The DateTime structure has a property DayOfWeek that returns an enum like DayOfWeek.Sunday. So here is a code fragment that may help:
var startOfWeek = DateTime(xx, yy ...); // defined by your business code
var firstDayOfWeek = startOfWeek.DayOfWeek;
var lastDayOfWeek = firstDayOfWeek.AddDays(6).DayOfWeek;
I have not compiled this code, straight off my head, so hope it is okay.

How to Compare two date without timeline in 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

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