My table contains 2 fields with values,
StartTime EndTime
3/6/2010 8:00:00 AM 3/6/2010 10:20:00 AM
Now I have a datepicker control wherein the user can select a date,
C# Logic:
DateTime SelDate;
if (datePicker.SelectedDate == null)
SelDate = DateTime.Now;
else
SelDate = datePicker.SelectedDate;
I am trying to compare dates by the below code but it gives me compile time error,
foreach (DomainObject obj in res.ResultSet)
{
MyClass adef = (MyClass)obj;
DateTime sTime = (DateTime)adef.StartTime;
DateTime eTime = (DateTime)adef.EndTime;
if ((SelDate.ToShortDateString >= sTime.ToShortDateString) && (SelDate.ToShortDateString <= eTime.ToShortDateString))
{
actdef.Add(new MyClassViewModel(adef));
}
}
I just want to take the date for comparison and not the time part. So I have used the ToShortDateString method.
Just use the Date property of DateTime:
if (SelDate.Date >= sTime.Date)
Also note that you can use DateTime.Today to get the start of today.
Just use the Date property of the DateTime and do a straight comparison.
DateTime SelDate = datePicker.SelectedDate == null ? DateTime.Now : datePicker.SelectedDate;
if( SelDate.Date >= sTime.Date )
{
// do something here
}
Related
Please advise how I can check that current date (DateTime.Now) is in diapason of dates in format "dd/mm". For example - 01.01 <= DateTime.Now <= 01.03 - Current date more that 1st of January but less that 1st of March
Let dateStrFrom be the first input ie, the From Date and dateStrTo be the second input ie, the To date. Then you can use DateTime.TryParseExact to convert it into the required DateTime Object for processing your comparison.
I hope that you are looking for something like this :
string dateStrFrom = "01.01";
string dateStrTo = "01.03";
DateTime dateFrom, dateTo;
DateTime.TryParseExact(dateStrFrom, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateFrom);
DateTime.TryParseExact(dateStrTo, "dd.MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTo);
if (dateFrom <= DateTime.Now && dateTo <= DateTime.Now)
{
// code here this will be the true condition for you
}
DateTime dt1 = DateTime.ParseExact("01/01", "dd/MM",null);
DateTime dt2 = DateTime.ParseExact("28/11", "dd/MM", null);
if (dt1 <= DateTime.Now && DateTime.Now < dt2)
{
MessageBox.Show("hi");
}
if someone find the solution, thanks
Try this:
DateTime.Compare(DateTime.Now, DateTime.ParseExact("01.03", "dd.MM", null))
This returns a signed number indicating the relative values of t1 and t2.Value Type Condition Less than zero t1 is earlier than t2. Zero t1 is the same as t2. Greater than zero t1 is later than t2.
You can parse using DateTime.Parse(). For your case you can using the DateTime.Compare()
Sample code will help you.
// If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/11/2016");
DateTime d2 = DateTime.Parse("01/01/2016");
if (d1.Date > d2.Date)
{
// do the stuff
}
// For Converting it to String
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
// Comparison
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
// Will give you a DateTime typed object
var dateTime = DateTime.Parse("01/01/2016");
I have a column in a table as PSR_LOAD_DATE_TIME which contains value of the format 2016-01-09 14:06:19
But the column is of type varchar(32).
I have a linq query to compare PSR_LOAD_DATE_TIME with a specific date alone. But it compares PSR_LOAD_DATE_TIME with time.
where (t0.PSR_LOAD_DATE_TIME.CompareTo(from_Date) >= 0) && (t0.PSR_LOAD_DATE_TIME.CompareTo(to_Date) <= 0)
Here from_Date and to_Date variable contains value like 2016-01-03.
So, I need to remove time portion from PSR_LOAD_DATE_TIME.
how to write the Linq query for that?
you could parse the DateTime expression in PSR_LOAD_DATE_TIME into a real DateTime and then use just the Date portion of that DateTime object.
void Main()
{
List<string> dates = new List<string>();
dates.Add("2016-01-18 12:05:12");
string from_Date = "2016-01-16";
string to_Date = "2016-01-18";
var date = from d in dates where (DateTime.ParseExact(d, "yyyy-MM-dd HH:mm:ss", null)
.Date.CompareTo(DateTime.ParseExact(from_Date, "yyyy-MM-dd", null)) >= 0 &&
DateTime.ParseExact(d, "yyyy-MM-dd HH:mm:ss", null)
.Date.CompareTo(DateTime.ParseExact(to_Date, "yyyy-MM-dd", null)) <= 0)
select d;
foreach(var d in date) {
Console.WriteLine(d.ToString());
}
}
I suppose you use EF to query this one.
So you should try
DbFunctions.TruncateTime
I want to compare two persian dates to find out which one is greater, I use this function :
public static List<MatchDrawHistory> GetAllMatchDrawHistory(string startDate, string endDate)
{
using (var db= new ReceiveSendEntitiesV5())
{
var matchDrawList = db.MatchDrawHistories.Where(x => String.CompareOrdinal(x.DrawStartDate,startDate)>=0 && String.CompareOrdinal(x.DrawEndDate , endDate) <=0).ToList();
return matchDrawList;
}
}
but it does not work, how can I do it?
EDIT: DrawStartDate and DrawStartDate are nvarchar(20) in DataBase, and these are persian date not gregorian date
First you need to convert your string date to DateTime. Assuming your string date is as yyyy/MM/dd, the conversion function can be as follow:
private static DateTime ParseDate(string date)
{
var pc = new PersianCalendar();
string[] arrDate = date.Split("/");
return pc.ToDateTime(Int32.Parse(arrDate[0]), Int32.Parse(arrDate[1]),
Int32.Parse(arrDate[2]), 0, 0, 0, 0);
}
Now you can use the following method to compare two dates:
private static bool Compare(DateTime firstDate, DateTime secondDate)
{
return firstDate >= secondDate;
}
Your problem is that you're trying to store the dates as strings. I presume the dates in your class are strings, so I would pass in a DateTime, and use something like the following:
var matchDrawList = db.MatchDrawHistories.Where(x => DateTime.Parse(x.DrawStartDate) >= startDate && DateTime.Parse(x.DrawEndDate) <= endDate).ToList();
If you're not sure that the string will resolve to a date correctly, you could create a function to wrap a TryParse, depending on your business logic this may be preferable, as presumably you still want other results if one has an invalid date.
static bool CheckDateGreater(string date1, string date2)
{
DateTime dt1;
if (!DateTime.TryParse(date1, out dt) return false;
DateTime dt2;
if (!DateTime.TryParse(date2, out dt) return false;
return (dt1 >= dt2);
}
Then call:
var matchDrawList = db.MatchDrawHistories.Where(x => CheckDateGreater(x.DrawStartDate, startDate) && CheckDateGreater(endDate, x.DrawEndDate).ToList();
EDIT:
Just seen your comment about Persian date. You need to use the PersianCalendar class. That should return you a DateTime object.
Use DateTime for the comparison rather than string
var start = DateTime.Parse(startDate);
var end = DateTime.Parse(endDate);
...
db.MatchDrawHistories.Where(x => x.DrawStartDate >= start && x.DrawEndDate <= end)
Use CompareTo method like below code:
if(endDate.CompareTo(startDate) < 0)
//startDate is greater
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;
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))
{
}