I am trying to get some date in between two different days:
$t = TrackingCode::where("organization_id", 10)
->whereBetween("tracking_codes.created_at", [Carbon::parse('2018-02-12 00:00:00'),
Carbon::parse('2018-02-13 23:59:59')])->get()->toArray();
I have one row where created at its 2018-02-13 13:33:41 but its not working I get an empty array/collection back;
I've also tried this so far without any success:
where("created_at", ">",Carbon::parse('2018-02-12 00:00:00'))
->orWhere("created_at","<", Carbon::parse('2018-02-13 23:59:59')
I used to chain whereDate()->whereDate() to mimick the whereBetween functionality. You might also consider moving this logic to a query scope on the model.
$query
->whereDate("tracking_codes.created_at", ">", Carbon::parse('2018-02-12 00:00:00')
->whereDate("tracking_codes.created_at", "<", Carbon::parse('2018-02-13 23:59:59')
->get()->toArray();
But maybe you can try to convert the carbon instances to a datetimestring via Carbon::parse('2018-02-12 00:00:00')->toDateTimeString().
$t = TrackingCode::where("organization_id", 10)
->whereBetween("tracking_codes.created_at", [Carbon::parse('2018-02-12 00:00:00')->toDateTimeString(),
Carbon::parse('2018-02-13 23:59:59')->toDateTimeString()])->get()->toArray();
Have you tried with created_at instead of tracking_codes.created_at?
$t = TrackingCode::where("organization_id", 10)
->whereBetween("created_at", [Carbon::parse('2018-02-12 00:00:00'),
Carbon::parse('2018-02-13 23:59:59')])->get()->toArray();
Your code should work, but I saw this difference. Perhaps can help you.
In fact, the main problem in carbon class that you use it's good with the front end or with showing the data, but when you talk to MySQL database you must be more formal, so you can use something like this:-
$firstDate = date('2018-02-12 00:00:00', time());
$lastDate = date('2018-04-05 00:00:00', time());
$t = TrackingCode::where("organization_id", 10)
->whereBetween("created_at", [$firstDate, $lastDate])->get();
Related
I'm trying to build a scheduler in which an incremental day addition and subtraction method is required.
Here, I am simply trying to add a day to this variable (which is displayed to the user elsewhere) each time this function is executed via a button I set up that routes to a certain location. But, I keep getting this error
Call to a member function addDay() on integer
whenever I try to execute this. I am new to using the Carbon interface and looked through the documents, which led me to try parsing the function (worked when I had the same error with a string) but to no avail obviously. Any help is appreciated and/or a possible explanation of how this error is working really.
function addDay(){
$day = (int) Carbon::now()->format('j');
$day = $day->addDay();
}
Thanks in advance. If there is a better way to do this (adding days incrementally with the button/link), I would love to hear it. My logic seems flawed after working on the application the entire day.
You're casting the Carbon date object into an integer by using the (int) in the first $day variable. Therefor when you're trying to access the function addDay() it's failing, because $day is no longer a Carbon object but an integer.
$day = Carbon::now();
$day = $day->addDay()->format('j');
This should work, and if you need to cast it to an integer for some reason, then do it like this.
$day = Carbon::now();
$day = (int) $day->addDay()->format('j');
This way you cast the integer after you've added the day.
There is also a much cleaner approach to this syntax, which uses method chaining like so
$day = (int) Carbon::now()->addDay()->format('j');
As #Classified said but a cleaner approach would be to work with Carbon object first and then apply format on that.
Like this:
$dateObj = Carbon::now()->addDay();
$day = (int) $dateObj->format('j');
Cleaner approach and better readability.
What is the desired returned value ?
$day = Carbon::now()->addDay();
return $day->dayOfWeek; //day of the week, 03/08/18 (now) returns 6 (INT)
return $day->format('j'); //day of the month, 03/08/18 (now) returns "4" (STRING)
return $day->day; //day of the month, 03/08/18 (now) returns 4 (INT)
return $day //Carbon object (at now() + 24h) that you can manipulate
You have to addDay to Carbon instance not to the integer (the day) :
$dt = Carbon::create(2012, 1, 31, 0); // 2012-01-31 00:00:00
echo $dt->addDay(); // 2012-03-04 00:00:00
I have a table that has two dates fields, begin and end.
I'm trying to get all rows that have begun but not yet ended. and if today is less than begin, they shouldn't be included. and if today is grater than end they shouldn't be included.
I'm using laravels eloquent. Here is what i've tried
$now = \Carbon\Carbon::now();
$promos = \App\Models\LivePromo::
where("begin", "<=", $now)
->where("end", ">=", $now)
//Other conditions
->get();
This seemingly work, but it also selects rows that are greater have already ended.
How can i make this work as i expect?
EDIT
The begin column is a datetime column that signifies when the 'promo' should start, and the end column is a datetime column that signifies when the 'promo' should end. I'm just trying to get all valid promos for the current date and time
EDIT
Sample data
$now = '2017-02-24 10:29:10' // \Carbon\Carbon::now();
remove = from end date condition:
$now = \Carbon\Carbon::now();
$promos = \App\Models\LivePromo::
where("begin", "<=", $now)
->where("end", ">", $now)
->get();
Also, it might depend on your database engine.
Some engines require you to use the whereDate() method instead of plain old where()
$promos = LivePromo::whereDate("begin", "<=", $now)
->whereDate("end", ">", $now)
->get();
I need to fetch all the records which is inserted between past 3 hours to current(now). I am using laravel framework(eloquent orm).
I tried this found here
$lb = \DB::table('myTable')->whereRaw('created_at = DATE_ADD(NOW(), INTERVAL -3 HOUR');
But it return NULL. Is there any way I can do using eloquent but not Raw Query?
Any Help would be appreciated.
Laravel comes with Carbon, a nice library to handle dates, which can be used in combination with Eqlouent.
Example:
\DB::table('myTable')
->where('created_at', '>',
Carbon::now()->subHours(3)->toDateTimeString()
);
More Information
For more fun date methods, check out these docs on Carbon
http://carbon.nesbot.com/docs/#api-addsub
We can use PHP DateTime. Like this,
$date = new \DateTime();
$date->modify('-3 hours');
$formatted_date = $date->format('Y-m-d H:i:s');
$lb = \DB::table('myTable')->where('created_at', '>',$formatted_date);
In above code what we're doing is creating date string with PHP and using that in query.
add this scope to your model:
public function scopeRecent($query)
{
return $query-> whereDate('created_at ' , '=',Carbon::today())
->whereTime('created_at' , '>',Carbon::now()->subHours(3));
}
then use the scope in controller :
$posts= Post::recent()->pluck("id")->toArray();
Try This
$lb = \DB::table('myTable')->whereRaw('created_at >= DATE_SUB(NOW(), INTERVAL 3 HOUR)')
In your statement you are using = (206-07-27 11:30:00) instead >= (206-07-27 11:30:00)
try this,
include use Illuminate\Support\Facades\DB; namespace in your controller
and try this code
$results = DB::table('yourtable')->select('*')->where('created_at >= DATE_SUB(NOW(),INTERVAL 1 HOUR)')->get();
as created_at is datetime field, you can use this
\DB::table('myTable')->where('created_at', '<', Carbon::now()->subHours(3)->toDateTimeString())->get();
I have a web app written in Laravel 3. In this application one of the models is "Activities". These activities have both a start date and end date field. I was wondering what the best way is to query all Activities that start AND end the same day?
-- Update --
I'm using mySQL and the field types are both Timestamp...
What I have currently:
...
$activitySchedule = ActivitySchedule::with(array('location'))->where(function($query) {
// Query activities that start and end today
$yesterday = date('Y-m-d', strtotime('today')) . ' 00:00:00';
$tomorrow = date('Y-m-d', strtotime('today')) . ' 23:59:59';
$query->where('starts', '>', $yesterday);
$query->where('ends', '<', $tomorrow);
});
...
I think this works properly but I'm wondering if there is a more precise method?
You should be using Carbon package which would allow you to get startOftheDay and endoftheday like this:
$StartofDay = Carbon::now()->startOfDay();
$EndofDay = Carbon::now()->endOfDay();
Once you have this in place, query your model with a where condition involving a condition to check using StartofDay and EndofDay values along with created_at column.
Find carbon package here : https://github.com/briannesbitt/Carbon
Hope it helps.!!
I have a date returned from an sql query (a datetime type field) and want to compare it to today's date in PHP. I have consulted php manual and there are many ways to do it. I finally came up with a solution comparing strings, but I would like to know if there are either any 'better' (best practice), cleaner or faster ways to do it. This is my solution:
// $sql_returned_date='2008-10-17 11:20:04'
$today = new DateTime("now");
$f_today=$today->format('Y-m-d'); //formated today = '2011-03-09'
$sql_date=substr($sql_returned_date,0,9); //I get substring '2008-10-17'
if($f_today==$sql_date)
{
echo "yes,it's today";
}else{
echo "no, it's not";
}
thanks
Seriously guys?
//$mysql_date_string= '2013-09-20' OR '2013-09-20 12:30:23', for example
$my_date = new DateTime($mysql_date_string);
if($my_date->format('Y-m-d') == date('Y-m-d')) {
//it's today, let's make ginger snaps
}
You could factor this into the data returned from your database query:
SELECT `DateOnDB`,
DATE(`DateOnDB`) = DATE(CURDATE()) AS isToday
FROM `dbTable`
and simply use PHP to test the value of the isToday column
Excuse me for being a question-digger, but I was trying to achieve the same thing, and I found a simple solution - if you want to select only rows with today's date you can do :
WHERE DATE(datetime_column)=CURDATE()
in your mySQL query syntax.
You'd have three solutions :
Working with strings, like you are doing ; which seems like a solution that works ; even if it doesn't feel clean.
Working with timestamps, using strtotime() and time() ; which is a bad idea : UNIX Timestamps only work for dates that are greater than 1970 and lower than 2038
Working with DateTime everywhere ; which would both work and feel clean.
If I need to make any calculation on the PHP-side, I would probably go with the third solution -- but the first one would be OK in most cases, I suppose.
As a sidenote : instead of formating your date to Y-m-d, you could check if it's :
Greater of equal than today
Less than tomorrow.
If SQL returned date is in this format 2011-03-09 (date format without timing),
$sqlret = "2011-03-05";
$curdate = date('Y-m-d');
echo $diff = strtotime($curdate) - strtotime($sqlret);
echo $no_diff = $diff/(60*60*24);
If the date with time like:
$sqlret = "2011-03-05 12:05:05",
Just make your current date format also like that:
$curdate = date('Y-m-d H:i:s');
If it doesn't satisfies your need, ask your question with some example.
You can use new DateTime php Object that way.
$date1 = new DateTime('2012-01-21');
$date2 = new DateTime ( 'now');
$interval = $date1->diff($date2);
if( $interval->format('%R%a ') == 0){
echo 'it s today';
}
I'd do that:
# SQL
SELECT DATE_FORMAT(date_col, "%Y-%m-%d") AS created_at FROM table
# PHP
if ( date('Y-m-d') == $sql_date ) { // assuming $sql_date is SQL's created_at
echo 'today';
}
$time = //your timestamp
$start = mktime(0,0,0,date("j"),date("n"),date("Y"));
$end = mktime(23,59,0,date("j"),date("n"),date("Y"));
if($time > $start && $time < $end){
//is today
}