find difference between two date textboxes - c#

in my c# form i have two date text boxes on for borrow date and the other for return date
borrowed_date_txt , return_date_txt
i want to compare two text boxes to find difference between them and if the date of
borrowed_date_txt is greater than the date of return_date_txt i want to make the return_date_txt background red?

Parse them to DateTimes and TimeSpans and do your logic/comparisons with these. Then call ToString() in the result and you will get a default-formatted date and time. DateTime also provides very handy properties based on the dates.
See: http://msdn.microsoft.com/en-us/library/system.datetime(v=vs.110).aspx
EDIT: I am assuming this is a Windows Form and not a web form. I will revise if web is what you need.

You can use DateTime.Compare
int idiff = DateTime.Compare(DateTime.Parse(borrowed_date_txt), DateTime.Parse(return_date_txt));
if (idiff > 0) //borrowed_date_txt is greater than the date of return_date_txt
{
//Do what you need
}

you should convert string to date
then you could try this:
DateTime date1 = Convert.ToDateTime(borrowed_date_txt);
DateTime date2 = Convert.ToDateTime(return_date_txt);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else
relationship = "is later than";

Something like this should work for you.
System.TimeSpan = EndDate.Subtract(StartDate)
gives you the difference in days-hours-seconds-milliseconds. If you just want the difference in the # of days, you can specify that by using the Days property of the System.TimeSpan class.
DateTime StartDate;
DateTime EndDate;
TimeSpan Difference;
StartDate = Convert.ToDateTime(txtStartDate.Text.ToString());
EndDate = Convert.ToDateTime(txtEndDate.Text.ToString());
Difference = EndDate.Subtract(StartDate);
lblDifference.Text = Convert.ToString(Difference.Days);

Related

Adding days to only date and then subtracting it from date in c#

I know this topic has already been discussed but I want to add days to only date, not the complete datetime and then I need to subtract it with date. What I have done till now is :
string endDate = DateTime.Now.AddDays(2).ToShortDateString();
Now this gives me string like 19-jan-17 which is great but when I want to subtract it with todays date, it gives error because the end date is in string. I tried below code:
TimeSpan diff = DateTime.Now.ToShortDateString() - endDate ;
or
TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToDateTime(endDate)
or
TimeSpan diff = DateTime.Now.ToShortDateString() - Convert.ToString(endDate)
and if I change DateTime.Now.ToShortDateString() to DateTime.Now then it will also include time which I do not want. I just want to add days in date only and then subtract it with today's date.
Any suggestions. Please help.
Try this:
DateTime endDate = DateTime.Today.AddDays(2);
TimeSpan diff = DateTime.Today - endDate
The Today property will return only the date part (so time will be 00:00:00), but still in a DateTime struct, so you can get a TimeSpan from subtracting another DateTime from it.
Did you try doing the following?
string endDate = DateTime.Now.Date.AddDays(2);
Still, it is not clear why you have to do that. A bit of context would be great for proposing other solutions.
I join Federico, you need to use the Date property of the DateTime instance. It will return the 00:00:00 moment of the date.
One side note:
Just keep all dates in DateTime (e.g. do not convert them into strings) before calculating the diff.
e.g.:
TimeSpan diff = DateTime.Now.Date - endDate;
If you need the date part, you can use format strings after the calculation.
e.g.:
endDate.ToString("yyyy.MM.dd")

if else statement between datetime but disregard time

Can you help me in removing the time in my code or rather correct my code for possible errors.
Thanks. Here's my code and ill state the error later.
else if (this.dateTimePicker1.Value != DateTime.Now)
{
this.chkBxLessNinety.Enabled = false;
string dateInString = Convert.ToString(Convert.ToDateTime(_dr[4]));
DateTime startdate = DateTime.Parse(dateInString);
DateTime datelimit = startdate.AddDays(90);
//string date = Convert.ToString(Convert.ToDateTime(datelimit.Date).ToString("mm/dd/yyyy"));
string mydate1 = this.dateTimePicker1.Value.ToShortDateString();
if (mydate1 > datelimit)
{
MessageBox.Show("Cannot Sync data more or equal to 90 days");
}
else
{
}
the line if (mydate1 > datelimit) shows an error which says > cannot be applied as operand of type string an datetime.
Please help.
Thanks in advance.
You want to compare DateTimes with each other. Since you want to exclude the time portion then the Date property will make both dates at midnight hour.
DateTime mydate1 = this.dateTimePicker1.Value;
if (mydate1.Date > datelimit.Date)
{
MessageBox.Show("Cannot Sync data more or equal to 90 days");
}
Just remove .ToShortDateString()
And also:
string dateInString = Convert.ToString(Convert.ToDateTime(_dr[4]));
DateTime startdate = DateTime.Parse(dateInString);
Don't convert from DateTime to string and then back to DateTime, it's pointless
You can't use the > to compare a string and a DateTime. Instead, you should replace
string mydate1 = this.dateTimePicker1.Value.ToShortDateString();
with
DateTime mydate1 = this.dateTimePicker1.Value;
This way, you'll be comparing things of the same type (DateTime).

How to get Difference between SelectStartDate to SelectEndDate on monthcalender in C#

I m trying to get date count from month calender on C# .my code like this
leave.Amount = Convert.ToInt32((mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays.ToString());
I got error like this
Input string was not in a correct format.
TimeSpan.TotalDays property is of type double, you can get the integer part like:
leave.Amount = (int) (mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays;
Consider the following example:
double d = 123.22d;
int number = Convert.ToInt32(d.ToString());
The would result into the exception
Input string was not in a correct format.
So in your code, you can leave out the call ToString and it would be fine, like:
leave.Amount =
Convert.ToInt32(
(mclDateRange.SelectionEnd - mclDateRange.SelectionStart).TotalDays);
Here’s a step by step example on how to diff two datetime objects. Just apply this to your code
DateTime startDate = DateTime.Parse("01/01/2013");
DateTime endDate = DateTime.Parse("05/22/2013");
TimeSpan dateDiff = endDate.Subtract(startDate);
int dayDiff = dateDiff.Days;
If you want to round fractional days (like 4 days 18 hrs) days to the nearest one (5 in this case) then use TotalDays property and convert to Int.
This is the way i did for datetimepicker hope it will work to monthcalender
DateTime dt;
DateTime Todate ,FromDate;
Todate = DateTime.ParseExact(datetimepicker1.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
FromDate = DateTime.ParseExact(datetimepicker2.Value.Date.ToString("dd/MM/yyyy"), "dd/MM/yyyy", CultureInfo.InvariantCulture);
double datedifference = (Todate - FromDate).TotalDays;
Then can check as date checking like this
if(datedifference <2)
{
something ..........
}

Most efficient way to compare two dates; one with time, one without

I want to compare two dates; one taken from a Date column in SQL and the current DateTime.Now. The former has no time portion (technically it does, but it's zeroed out) and of course the later will have the current time to the nearest millisecond. Here is what I am doing now, and it seems inefficient:
DateTime compareDate = Convert.ToDateTime(string.Format("{0:M/d/yyyy}", DateTime.Now));
if (myObj.EndDate < compareDate)
{
myObj.Status = "PAST";
}
else if (myObj.StartDate <= compareDate && myObj.EndDate >= compareDate)
{
myObj.Status = "ACTIVE";
}
else
{
myObj.Status = "PENDING";
}
Is there a better way to strip time off a DateTime variable?
Yes, use the Date property of the DateTime structure, or just use DateTime.Today.
e.g.
DateTime compareDate = DateTime.Now.Date
or
DateTime compareDate = DateTime.Today
Use the property "Date" on the the DateTime variable you want to strip the time from.
var pureDate = DateTime.Now.Date;

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

Is there a way to compare two DateTime variables in Linq2Sql but to disregard the Time part.
The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.
I want to compare 12/3/89 12:43:34 and 12/3/89 11:22:12 and have it disregard the actual time of day so both of these are considered the same.
I guess I can set all the times of day to 00:00:00 before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.
I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?
try using the Date property on the DateTime Object...
if(dtOne.Date == dtTwo.Date)
....
For a true comparison, you can use:
dateTime1.Date.CompareTo(dateTime2.Date);
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime
If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime
Use either (based on your EF version) around any DateTime class property you want to use inside your Linq query
Example
var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate)
>= DbFunctions.TruncateTime(DateTime.UtcNow));
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
MessageBox.Show("Valid Date");
}
else
{
MessageBox.Show("Invalid Date... Please Give Correct Date....");
}
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}
You can use this if you are using nullable DateFields.
DateTime dt1=DateTime.ParseExact(date1,"dd-MM-yyyy",null);
DateTime dt2=DateTime.ParseExact(date2,"dd-MM-yyyy",null);
int cmp=dt1.CompareTo(dt2);
if(cmp>0) {
// date1 is greater means date1 is comes after date2
} else if(cmp<0) {
// date2 is greater means date1 is comes after date1
} else {
// date1 is same as date2
}
DateTime econvertedDate = Convert.ToDateTime(end_date);
DateTime sconvertedDate = Convert.ToDateTime(start_date);
TimeSpan age = econvertedDate.Subtract(sconvertedDate);
Int32 diff = Convert.ToInt32(age.TotalDays);
The diff value represents the number of days for the age. If the value is negative the start date falls after the end date. This is a good check.
In .NET 5:
To compare date without time you must use EF.Functions.DateDiffDay() otherwise you will be comparing in code and this means you are probably pulling way more data from the DB than you need to.
.Where(x => EF.Functions.DateDiffDay(x.ReceiptDate, value) == 0);
You can try
if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
....
In your join or where clause, use the Date property of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>) operation. This should allow you to compare dates without the time.
int o1 = date1.IndexOf("-");
int o2 = date1.IndexOf("-",o1 + 1);
string str11 = date1.Substring(0,o1);
string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
string str13 = date1.Substring(o2 + 1);
int o21 = date2.IndexOf("-");
int o22 = date2.IndexOf("-", o1 + 1);
string str21 = date2.Substring(0, o1);
string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
string str23 = date2.Substring(o2 + 1);
if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
{
}
else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
{
}
else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
{
}

Categories

Resources