Query formatted value using LINQ - linq

I have to query a Date column with formatted values. Consider a scenario, same date with different timing "05/12/2012 02:00:00" and "05/12/2012 12:00:00". I have to query this collection such that resultant should have only date and not time "05/12/2012"(dd/MM/yyyy).
datasource.AsQueryable().Select("Date").Cast<object>().Distinct().ToList<object>();
I have used the above to get collection and i am not able to get the formatted collection.
Thanks.

Why not just juse the Date property of DateTime?
datasource.Select(d => d.Date.Date).Distinct()
I can't figure out what you're trying to do with the Cast.

Related

How to return a query from cosmos db order by date string?

I have a cosmos db collection. I need to query all documents and return them in order of creation date. Creation date is a defined field but for historical reason it is in string format as MM/dd/yyyy. For example: 02/09/2019. If I just order by this string, the result is chaos.
I am using linq lambda to write my query in webapi. I have tried to parse the string and try to convert the string. Both returned "method not supported".
Here is my query:
var query = Client.CreateDocumentQuery<MyModel>(CollectionLink)
.Where(f => f.ModelType == typeof(MyModel).Name.ToLower() && f.Language == getMyModelsRequestModel.Language )
.OrderByDescending(f => f.CreationDate)
.AsDocumentQuery();
Appreciate for any advice. Thanks. It will be huge effort to go back and modify the format of the field (which affects many other things). I wish to avoid it if possible.
Chen Wang.Since the order by does not support derived values or sub query(link),so you need to sort the derived values by yourself i think.
You could construct the MM/dd/yyyy to yyyymmdd by UDF in cosmos db.
udf:
function getValue(datetime){
return datetime.substring(6,10)+datetime.substring(0,2)+datetime.substring(3,5);
}
sql:
SELECT udf.getValue(c.time) as time from c
Then you could sort the array by property value of class in c# code.Please follow this case:How to sort an array containing class objects by a property value of a class instance?

Laravel Query Builder - Where date is now using carbon

How to get only date on database column, I have difficulties using Carbon on controller:
$data['nowUser'] = User::where('date', Carbon::today()->toDateString())->get();
Date column looks like this in the database:
That is a DATETIME column, so there's no need for additional formatting the Carbon instance. However you need to use whereDate if you want the fetch all users for which the date column contains today's date:
$data['nowUser'] = User::whereDate('date', '=', Carbon::today())->get();
Because when you pass Carbon::today() to the Query Builder method, the __toString method will be automatically called and return a DATETIME string with the format from Carbon::DEFAULT_TO_STRING_FORMAT, which is exactly that MySQL format Y-m-d H:i:s.

Extract only date part in a datetimein LINQ

We have some data in a DataTable and we are using the query like this to get what we need.
IEnumerable<Results> subResult = from query in datatable.AsEnumerable()
select new Results
{
Name = query.Field<string>("Name"),
Date = query.Field<DateTime?>("Date")
}
This above query returns what i need but date in full format (Ex: m/dd/yyyy hh:min:sec am/pm) but we need only date part of it(only mm/dd/yyyy need to be pulled in). When looked in the properties of this, couldn't find an implicit way to get it, please help me in getting this result. Thanks.
The DateTime class has all the properties you just mentioned. You should try to fix your display with the ToString("anyformatyouwant") formats.
What about this?
Date = query.Field<DateTime?>("Date").Date
This will give you just the date part:
IEnumerable<Results> sub-result= from query in datatable.AsEnumerable()
where new Results
{
Name = query.Field<string>("Name"),
Date = query.Field<DateTime?>("Date").Date
}
However if you just want to display the date somewhere (meaning you're not using this to do date grouping, etc. then I would just specify the display format in your UI layer.
AFAIK there is no Date Class in .net, if you want pure date you should write a Class for that, otherwise you can pull out the part as a string
DateTime.Now.Date.ToString("yyyy/MM/dd")
gives you the current date in string type, but if you get the .Date part it gives you a DateTime object which still has a time part showing AM 12:00:00:0 blah blah

Rails ActiveRecord Find / Search by Date

I am trying to find records by 'created_at' date - the database column type is 'datetime' and
I am using the UI DatePicker from jQuery
my url look like this: "localhost:3000/users_supported?selected_date=2012-10-31"
So far i am doing good :) and my query in controller looks like this:
#support_histories = current_agent.support_histories.where(:created_at => Date.parse(params[:selected_date]))
How to properly extract records by 'date' only from the 'datetime' db column
I tried doing this in Rails Console, but no luck there:
sh = SupportHistory.where(:created_at => DateTime.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => Date.parse('2012-10-31'))
sh = SupportHistory.where(:created_at => DateTime.strptime('2012-10-31', '%Y-%m-%d'))
I got records if i do like mentioned below, but that's not useful to me as i am trying to find record by 'date' not by 'DateTime'
sh = SupportHistory.where(:created_at => '2012-10-31 19:49:57')
selected_date = Date.parse(params[:selected_date])
# This will look for records on the given date between 00:00:00 and 23:59:59
sh = SupportHistory.where(
:created_at => selected_date.beginning_of_day..selected_date.end_of_day)
Time Zones may be a concern you need to look into, but this should work if all your times are in the same time zone.
A simple solution I use sometimes is to cast the date(time) field as text on the database rather than parse the string into date on application side. For your case that would be:
where('CAST(created_at AS text) LIKE ?', params[:selected_date])
Might not be the most effective on the database (depending on the context you use it in) but saves a lot of pita on the application side.
I solved this problem by creating a method in model like below,
Say, my model is ticket.rb
def created_date
self.created_at.to_date
end
then I queried like this,
selected_date = Date.parse(params[:date])
Ticket.all.map{|t| t if t.created_date == selected_date}.compact
This gives me accurate results that matches with the chosen date by the user.
Your current query doesn't work because you are querying a date on a datetime column. Those are two different data types.
For a datetime column, you'll need a datetime filter. You can do this by passing a DateTime object to the where clause. However, in your case you want records for the entire day so you'll specify a range between 00:00:00 and 23:59:59.
Before Rails 5.1:
SupportHistory.where(created_at: date.beginning_of_day..date.end_of_day)
Rails 5.1 and onwards: (this will generate the exact same range using #all_day)
SupportHistory.where(created_at: date.all_day)
If you want to parse a specific datetime
SupportHistory.where("created_at>=?", DateTime.parse('10 Dec 2021 11:54:00 PST -08:00'))

Is there anyway I could use nullable datetime property to get the year?

I am trying to perform the following linq to entities query-
var data = DataContext.Employee.Where(e=>e.Date.Year>1986).ToList();
Now the problem is that Date field is a nullable DateTime field and I can't access Year property and on the database side I can't change legacy code! ....anyways is there anyway possible to use the year property?
var data = DataContext.Employee
.Where(e=>e.Date.HasValue && e.Date.Value.Year>1986).ToList();
Note that this will not include Employees without a date in the list.

Resources