I am trying to add a date conditional to my controller index action:
#events = Event.where("date" => Date.today.to_s).order("date").page(params[:page]).per_page(5)
I am trying to make my view only show events that have a date value greater than or equal to today's date. For example if an event has a date value of 2013-05-13 it should not be shown because that event has already happened and only events with a date value of today's date or later should be shown.
The problem is, the index view isn't returning any events and I have created an with a date value of 2013-05-30 which means it should work. Any ideas?
Thanks in advance
This is actually going to return everything where the date equals today:
Event.where("date" => Date.today.to_s)
What you probably want instead is:
Event.where("date >= ?", Date.today)
ActiveRecord will interpolate the date into the ?. Also, you don't need to call to_s on it, ActiveRecord will the date for you.
Try this:
In your model use a scope like so:
scope :recent_event, lambda { where('date >= ?', Date.today ) }
Then in your controller write
#events = Event.recent_event.order("date").page(params[:page]).per_page(5)
Related
I want to change the value of field ( that changes to the date of the day for example)
automatically or when you access an already created view the action is generate in odoo13.
Thaks
You should use fields_view_get method, it will fired with every type of view, if you need it when a form is open you can do something like this:
#api.model
def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
res = super(Movimiento, self).fields_view_get(
view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu
)
if view_type == 'form':
# Get today date
today = fields.Date.context_today(self)
# update your field here.
return res
I hope this answer can be helpful for you.
I'm trying to get day of week from a variable that is found by maxid, but I only get this error:
Trying to get property 'dayOfWeek' of non-object
Code:
$dailyLog = DailyLog::with(['todoList','user'])->find(\DB::table('daily_logs')->max('id'));
$weekday = $dailyLog->date->dayOfWeek;
$yesterdaysLog = DailyLog::loadByDate(Carbon::now()->subMonth(1)->next($weekday));
I am trying to get the day of week from the first query and compare it to last months same day of week
This: $dailyLog->date is not a Carbon object most probably, hence the reason why you cannot call dayOfWeek.. make sure that the date returns a Carbon instance.
To do that in your DailyLog model add this :
protected $dates = ['date'];
This will make sure that the date is cast to Carbon. But also make sure that for some reason that field is not null also.
I want to return values in my model based on dates but not sure how to?
Logic
calculate the date that post has published + 7 days after that and return true or false.
example
Let say I want add new label in posts from the date that post published till 7 days after that, and in the day 8th that new label be removed.
How do I do that?
Update
I ended up with something like this in my model currently
public function isNew($query){
return $query->where('created_at', '<=', Carbon::now()->toDateTimeString());
}
but it returns Undefined variable: isNew in my blade.
please give me your suggestions.
Are labels stored in a separate table from your posts? You could use 'effective dating'. Have indexed 'show_at' and 'hide_at' fields in your labels table. Have entries there get created as soon as the post does. You could use database triggers to do this, or model observers. And when querying for all labels related to a given post, make sure they're between those dates (or those dates are null).
For a more simple solution, you could do a whereRaw('CURRENT_DATE <= DATE_ADD(dateFieldName, INTERVAL 7 DAY)'). If timezones are a factor, you could use the CONVERT_TZ() function, though it's generally good practice to store everything in UTC to avoid those issues.
I would recommend you make use of Carbon:
https://carbon.nesbot.com/docs/#api-difference
That link should help a lot but to point you in the correct direction, you should be able to do a comparison:
I assume you DB date is held in ISO (Y-M-D, eg: 2019-01-07)
$date= Carbon::createFromFormat('Y-m-d', $dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Or if you are using timestamps:
$date= Carbon::createFromTimestamp($dateFromDB);
if($date->diffInDays(Carbon::now() < 8){
Code for Add Label here
}
Solved
thanks for all the helps I solved my issue with code below:
public function getisNewAttribute(){
$now = Carbon::now();
return Carbon::parse($now) <= Carbon::parse($this->created_at)->addDays(7);
}
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
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'))