Date compare in LINQ - c#

i was looking for date compare in LINQ and i found a code from searching google.
var currentDate = DateTime.Now.Date;
VisitorLog log = db.Context.VisitorLogs
.Where(vl=>vl.inDate.Date == currentDate).FirstOrDefault();
i need to know the above code works fine or not.
how do i compare date in particular format like i compare date in sql server
compare(varchar(10),mydatefield,112)>=compare(varchar(10),#mydatefield,112)
so please guide me how could i compare date using linq in particular format like above one.
thanks

The thing is that you will rarely compare dates in a specific format(unless you want to compare them as strings or something). Thus is the introduction of the DateTime structure.
Anyway the most used way of comparing dates is not to check for equality but to actually check whether a date comes into a specific range. For example:
startDate <= order.OrderDate && order.OrderDate < endDate

Can this link help you?
How to compare dates in LINQ?
where t.CreateDate.Date < DateTime.Today.AddMonths(-1)

The format matters when you parse a string to a DateTime object. Once you have done that and you have two DateTime objects then comparing their Date properties is the correct thing to do. The Date properties return DateTime objects with time set to 12:00am
In order to parse the date correctly you can pass a IFormatProvider to the DateTime.Parse() method. E.g. a CultureInfo object:
DateTime d = DateTime.Parse("07/04/2011", CultureInfo.GetCultureInfo("en-us"));

Related

Store DateTime.Now to ddMMyyyy format without string operation

Is there any possible way for saving DateTime.Now to ddMMyyyy format without using ToString(). Because whenever I use the string operation the statement is not accepted by entity framework. I need to add DateTime to DB in date format of ddMMyyyy. Is there any way??
It would be silly and counterproductive to store dates as "ddMMyyyy". First of all you'd need a varchar(8), not a DATE or DATETIME.
On top of that, how are you ever going to sort it using ORDER BY, or use BETWEEN queries, or do myDate > someValue / myDate < someValue queries? You can't with a date-string formatted like that.
Also a notation such as "ddMMyyyy" is a User Interface representation of an underlying value. Databases should almost never store User Interface representations, that is a job for the... you guessed it... User Interface.
Best to just forget about it, or else be ready to face the horrible consequences.
Change you SQL Server Database data type from "datetime" to "date" ?
From the article for the DateTime.Parse() method (MSDN Article)
So you can do:
var dateTime = DateTime.Parse("01012001");
Which will give you a DateTime typed object.
If you need to specify which date format you want to use, you would use DateTime.ParseExact (MSDN Article)
Which you would use in a situation like this (Where you are using a British style date format):
string[] formats= { "ddMMyyyy" }
var dateTime = DateTime.ParseExact("01012001", formats, new CultureInfo("en-US"), DateTimeStyles.None);
The format "ddMMyyyy" (or any other format) makes any sense only if we're talking about strings.
If you need only the day, month, and year in the program you can still use the DateTime class.
You simply ignore the other properties like minutes, hours, etc...
DateTime now = DateTime.Now;
Method(now.Day, now.Month, now.Year);
or
DateTime emptyDateTime = new DateTime();
// in this case emptyDateTime values are the following:
emptyDateTime.Year: 1
emptyDateTime.Month: 1
emptyDateTime.Day: 1
emptyDateTime.Hour: 0
emptyDateTime.Minute: 0
emptyDateTime.Second: 0

Is there a way to format a date time object?

So last week, the way our application worked was that the back-end team was storing dates as a string in YYYY-MM-DD formats. This week, they changed it to be a DateTime object instead of a string. So now I'm just creating a DateTime object from the string value on this particular DateTime control we use.
So basically with our custom control , it was like this:
mySearchModelObject.fromDate = myDateRangeControl.Values[0]; //string
mySearchModelObject.toDate = myDateRangeControl.Values[1]; //string
Now it's more like this:
DateTime fromDate, toDate;
DateTime.Tryparse(myDateRangeControl.Values[0], out fromDate);
DateTime.Tryparse(myDateRangeControl.Values[1], out toDate);
mySearchModelObject.fromDate = fromDate;
mySearchModelObject.toDate = toDate;
But searching with the same date range as last week yields different results from the DB.
I'm wondering if it's because our dates were "YYYY-MM-DD" as strings, but now it's getting a date time object in whatever the system's format is + the time itself.
So is there a way to format my DateTime object to still have it in the same YYYY-MM-DD format?
Use DateTime.TryParseExact and provide "yyyy-MM-dd" as format string.
See http://msdn.microsoft.com/en-us/library/h9b85w22
you can do fromDate.ToString("yyyy-MM-dd") to have a date formatted as YYYY-MM-DD
see msdn on standard and custom datetime format
see demo https://dotnetfiddle.net/NZz0HG
also if mySearchModelObject.fromDate is of type object, you can assign a DateTime or a string, no compiler warnings/error.
But when is used, maybe with mySearchModelObject.fromDate.ToString() you get a different result, before was '2014-12-31' and now 12/31/2014 12:00:00 AM

Querying with Arabic (Hijri) DateTime

I essentially have a query that looks like this:
.Where(x=>x.Date < DateTimeOffset.UtcNow)
Now, this has worked as intended so far, but since also adding Arabic into my application, apparently their calendar system uses something called a Hijri calendar?
Anyway, date such as 24/09/2013 looks like 18/05/34 (invented values).
So, the query would end up using the 18/05/1834 date, and thus return no values.
tl;dr I want to be able to query with the non-cultured datetime.
I've tried to google how to use CultureInvariant, but all the solutions showed a .ToString() whereas I need a datetime returned
DateTime and DateTimeOffset don't have any culture. You only use culture info when parsing a string or outputting a string. Internally, they always store their data using the Gregorian calendar. So if you are comparing DateTime or DateTimeOffset values, then it doesn't matter what calendar system is used for display - the comparison will always be done with their Gregorian equivalents.
You had said in your question:
So, the query would end up using the 18/05/1834 date, and thus return no values.
If you are doing things normally, that won't be true. You won't have Hijri formatted dates in your database. Those will all be Gregorian still and the comparison should work as expected. If for some reason you actually have the Hijri values in your data, then somewhere you are passing your values by string, which is getting affected by culture. You shouldn't do that.
Take a look at the sample code in this MSDN entry. It shows clearly that you need to use a calendar object to get numerical equivalents for each part, but there is no way to get back a single non-string value that represents the entire date in a non-Gregorian calendar system.
For example:
DateTime utc = DateTime.UtcNow;
Calendar cal = new HijriCalendar();
int y = cal.GetYear(utc);
int m = cal.GetMonth(utc);
int d = cal.GetDayOfMonth(utc);
Or, as a string:
DateTime utc = DateTime.UtcNow;
var ci = CultureInfo.CreateSpecificCulture("ar-SA");
string s = utc.ToString(ci);
If you want a better way to represent Hijri calendar dates in your code, you might consider using Noda Time instead of the built-in types. It has much better support for alternative calendars. For example:
Instant now = SystemClock.Instance.Now;
CalendarSystem cal = CalendarSystem.GetIslamicCalendar(IslamicLeapYearPattern.Base15, IslamicEpoch.Civil);
ZonedDateTime zdt = now.InZone(DateTimeZone.Utc, cal);
LocalDateTime ldt = zdt.LocalDateTime;
UPDATE
It appears the question was with specific regard to querying in RavenDB, and was discussed here. The problem was tracked down to a culture related bug in RavenDB, and fixed in release 2.5.2715.

C# Compare Months

I am trying to check if the selected month is already past.
if (Convert.ToDateTime(DDMonths.SelectedItem.Text).Month > DateTime.Now.Month)
{
//logic here if date is not in the past
}
DDMonths.SelectedItem.Text value is April
However I am getting the following Format exception error:
String was not recognized as a valid DateTime.
You can parse the month by name with the following:
DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture ).Month
However, you'd be better off making the Value of each element in DDMonths the integer value corresponding to the month instead, if possible.
Convert.ToDateTime cannot understand your date format, you need to use DateTime.ParseExact instead:
if(DateTime.ParseExact(DDMonths.SelectedItem.Text, "MMMM", CultureInfo.CurrentCulture).Month > DateTime.Now.Month) {
...
}
it means that your line
Convert.ToDateTime(DDMonths.SelectedItem.Text)
is giving you error. You should use
DateTime.ParseExact(DDMonths.SelectedItem.Text,"MMMM",CultureInfo.InvariantCulture);
So the Text of your DropDownList-Item is not convertible to DateTime with the current culture. So maybe you are showing the month-name (what i assume) or the error is more subtiel. You could use the ListItem.Value to store the datetime in a specific format, for example:
"yyyyMMdd" -> "20130726"
Then you can parse it in this way:
var dt = DateTime.ParseExact("20130726", "yyyyMMdd", CultureInfo.InvariantCulture);
If you want to allow the monthname:
dt = DateTime.ParseExact("July", "MMMM", CultureInfo.InvariantCulture);
Since you are just looking for the number of the month, why parse it to a DateTime at all? You can just get it from the DateTimeFormatInfo directly:
string input = "April";
var months = DateTimeFormatInfo.CurrentInfo.MonthNames;
var monthNumber = 1 + Array.FindIndex(months, x => x.Equals(input, StringComparison.CurrentCultureIgnoreCase));
if (monthNumber > DateTime.Now.Month)
{
// ...
}
Do think about what you want to do if it is currently April. Depending on what you are doing, you may want to compare using >=.
Also, if you are writing a desktop application, this code (and the others) are just fine. But if you are writing a web application and this code is running server-side, then you have two additional concerns:
The culture should match the input. You may need to use a different culture, or the InvariantCulture.
You are comparing to DateTime.Now - which will be in the server's time zone. So if a user in another part of the world uses this on the 1st of their new month while your server is still on the prior day, then your comparison will fail.
You should be using a ParseExact variant of DateTime
DateTime.ParseExact("April", "MMMM", CultureInfo.InvariantCulture).Month // outputs 4
you should also try using the Value (DDMonths.SelectedItem.Value) component and fill it as needed

Convert string to a valid MS SQL datetime to use for search in database

I saw a lot of answers, most of which include using of DateTime.ParseExact and "CultureInfo.InvariantCulture` but it's not working for me and I'm not sure that those answers are 100% related to the problem I need to solve.
I have table with records from the database. The use can perform search based on different criteria one of which is date. I use some inherited jQuery calendar and in my controller the data from the date filed comes in format "dd/mm/yyyy hh:mm:ss". I want to be able to use this information to perform search in the database for records on the same date. The one problem is that I want to use only the date but not the time, but I'm not sure in what order to solve this problem so I decided to convert the incoming string to valid MS SQL datetime and see what happen and the to think about the time.
I tried different things, this is my last after which I decide to post here :
if (!String.IsNullOrEmpty(selDate))
{
CultureInfo myCItrad = new CultureInfo("bg-BG", false);
DateTime parsedDate = DateTime.ParseExact(
selDate,
"dd.MM.yyyy hh:mm:ss",
myCItrad);
model = model.Where(m => m.Date == parsedDate);
}
when I parse selDate the string doesn't contain them, it's - "23/05/2013 09:04:45"
If your input string looks like "23/05/2013 09:04:45" then you should use this pattern for ParseExact: "dd/MM/yyyy hh:mm:ss"
if (!String.IsNullOrEmpty(selDate))
{
CultureInfo myCItrad = new CultureInfo("bg-BG", false);
DateTime parsedDate = DateTime.ParseExact(
selDate,
"dd/MM/yyyy hh:mm:ss",
myCItrad);
model = model.Where(m => m.Date == parsedDate);
}
Leron,
Date issues between application and SQL are well known.
SQL and .NET date time types are different:
http://msdn.microsoft.com/en-us/library/system.data.sqltypes.sqldatetime.aspx
On both SQL and .NET there are numerous date time formats, all need to be treated as numbers types.
So, you need to know how to convert numerous date time formats on .NET side, to convert it to SQL type, and vice versa. Not a good practice...
Use SqlDateTime to conduct conversion.
Or:
A simple, a bit "dirty" solution, is something like that:
Take the date wanted by user. Calculate how many days is it from
current (e.g. --> int days = (DateTime.Now-selectDate).Days;
Now on database query, do it using SQL: GetDate()-days
The one problem is that I want to use only the date but not the time,
This has nothing to do with SQL date formats.
If you want to use only the date and not the time, you could do something like:
model = model.Where(m => m.Date.Date == parsedDate.Date);
or if you prefer:
model = model.Where(m => (m.Date >= parsedDate.Date && m.Date < parsedDate.Date.AddDays(1));
In the above m.Date.Date and parsedDate.Date you are using the DateTime.Date property to get the date component of your date value, discarding the time component.
DateTime in SQL is this format yyyy-MM-dd HH:mm:ss. correct code is
DateTime parsedDate = DateTime.ParseExact(selDate, "yyyy-MM-dd" myCItrad);

Categories

Resources