if else statement between datetime but disregard time - c#

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

Related

How to convert informal string value to Date time in c#

All of my friend.
I want to convert informal string to dateTime in c#. Here my string value is "01042016".How can convert? can i need another step to change DateTime.
This is my code:
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));
As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
// Proceed with the startDate it will have the required date
}
else
// Show failure message
This will create an Enumerable where index 0 is the first date and index 1 is the second date.
string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
.Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);
If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()
You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.
It is best to specify a required date format if you can so you can be sure the date was parsed correctly.
if you string is in static format, you can convert it by reconvert it to valid string format first such as
string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));

How to subtract DateTime field and Duration?

I have one field in database in this format: 2013-06-18 17:00:00.000
and second field Duration in this format: 3000 (this represents seconds, so it is 50 minutes)
I need to subtract those two fields and to set in another field result which will be: 2013-06-18 16:10:00.000
One addition is that they both can be retrieved from database in string format only. So they are both strings.
Thanks
First you need to Parse the datetime. Then subtract using AddSeconds:
var date = DateTime.Parse("2013-06-18 17:00:00.000");
var newDate = date.AddSeconds(int.Parse("-3000"));
You can use newDate.ToString() to get the date as a string.
You can find the documentation for DateTime here.
Update: Changed seconds to a string value. Which uses Parse to convert to an integer.
You can subtract to the datetime object. (if is a DateTime Type) if not, you should parse.
To handle errors, I would recommend to use DateTime.tryParse(value, out dateTime);
DateTime parsedDateFromBD;
if(DateTime.tryParse("2013-06-18 17:00:00.000", out parsedDateFromBD)
{
// do Stuff
}
else
{
// do something else
}
if you get it as a datetime from the db you can simply:
var calcDate1 = dateFromBD.addSeconds(3000); //to Add
var calcDate2 = dateFromBD.addSeconds(-3000); //to subtract
Cheers
Ricardo
In addition to the other answers here is how to parse the newDate to string that mach the required output
string date = "2013-06-18 17:00:00.000";
string duration = "-3000";
int durationSeconds = int.Parse(duration);
var newDate = DateTime.Parse(date).AddSeconds(durationSeconds).ToString("yyyy-MM-dd HH:mm:ss.fff");
The output is
//2013-06-18 16:10:00.000
Here you can find more about DateTime.ToString()

find difference between two date textboxes

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

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