I have a table mdl_forum_posts with a field created that's a BIGINT (database is not mine, so don't blame for the type of field). An example of value is 1504170577. The value is saved as a timestamp.
There will run a cron every Monday (first day of the week) that needs to select all the rows created in the previous week (created value in week before).
I'm trying to do this:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$postsNL = DB::table('mdl_forum_posts')->whereBetween('created', array($agoDate,$currentDate))->get();
But this isn't returning any rows (and it should!).
Keep in mind that when you do some operations on a Carbon object it will modify the instance of the object itself, so basically when you run the statement
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
you are also modifying $currentDate.
The below code should do the trick:
$currentDate = \Carbon\Carbon::now();
$agoDate = $currentDate->copy()->subDays($currentDate->dayOfWeek)->subWeek()->setTime(23, 59, 59);
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
The copy method will make all the modifications on a copy of the Carbon instance, not affetting the original one.
Hope it helps
Why should it? MySQL won't just compare an integer to a date. The integers are called unix timestamps and you can easily get unix timestamps out of Carbon by using the timestamp property on a Carbon instance:
$postsNL = DB::table('mdl_forum_posts')
->whereBetween('created', array($agoDate->timestamp, $currentDate->timestamp))
->get();
Since Carbon extends DateTime, you could also use the getTimestamp method.
Related
In my Laravel project I have a MySQL database table with the following column:
| requested_at |
2018-02-03 12:00:00
2018-03-03 11:00:00
I want to get all items from this column where the timestamp (requested_at) is older than 60 days:
$now = Carbon::now ();
$60days = DB::table('exampletable')->where('requested_at', '=', $now->subDays(60))->get();
For my following code I need to format the Date format from my column requested at.
I only want to get the date like this 2018-03-03 without the time.
I play around with some carbon methods but It didn't work at all:
$format60 = Carbon::createFromFormat('Y-m-d', $60days);
It seems that you are using TIMESTAMP type so
->where('requested_at', '<=', now()->subDays(60)->startOfDay())->get();
As you can see there is no need to format Carbon instance.
Break it all down:
now() // Laravel helper to get Carbon::now()
->subDays(60) // subtract 60 days
->startOfDay() // set time part of timestamp to start of the day
Note: add requested_at into $dates array in your model for easier use
You can achieve this by mysql only, no need of carbon.
Just using datediff() and now() of mysql.
Do like this
$days60 = DB::table('exampletable')
->whereRaw('datediff(now(),requested_at) = 60')
->get();
Example :-
Good day everyone,
I'm currently realising a system that lets colleagues fill in their worked hours and what they worked on. I save those into the database using a time_stamp (date) named in the table. Now I have been trying to get the values of the filled in registrations of last week (I created some dummy times). And I have been trying to use Carbon and the Eloquent query builder at the same time, and i'm completely stuck. Would anyone mind to help me out?
$currentDate = \Carbon\Carbon::now('GMT+2');
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
$weekly = Hoursregistration::pluck('date')->agoDate($currentDate);
return $weekly;
Is the code that should pick up the dates from the db (which works). But when I try to put in the variables containing the carbon methods. It doesnt work and throw me a Method agoDate does not exist. (View: /var/www/clients/client0/web319/web/resources/views/hoursregistrations/index.blade.php) error.
I would love some help as this is crucial to my education (kind of in a tight spot rn.)
As you ask for: all Hoursregistration records from 1 week ago until now
// Current date + GMT(+2) as stated in your question
$currentDate = Carbon::now('GMT+2');
// Date exactly 1 week ago
$agoDate = $currentDate->subDays($currentDate->dayOfWeek)->subWeek();
// Records with date -between- two values
// $weekly = Hoursregistration::whereBetween('date', [$agoDate, Carbon::now('GMT+2')])->get();
// Or even simpler, all records where date is 'higher' than 1 week ago
$weekly = Hoursregistration::where('date', '>', $agoDate)->get();
// Getting the dates with the `pluck` method on the returned $weekly collection
$dates = $weekly->pluck('date');
return $weekly;
How can I add a number of days to a DateTime object without modifying the original. Every question on StackOverflow appears to be about date and not DateTime, and the ones that do mention DateTime talk about modifying the original.
Eg.
$date = new DateTime('2014-12-31');
$date->modify('+1 day');
But how can you calculate a date several days in advance without modifying the original, so you can write something like:
if($dateTimeNow > ($startDate + $daysOpen days) {
//
}
I could always just create another DateTime object, but I'd rather do it the above way.
Use DateTimeImmutable, it's the same as DateTime except it never modifies itself but returns a new object instead.
http://php.net/manual/en/class.datetimeimmutable.php
you can take the original variable in a separate variable and add no. of days in other variable so you have both(original and updated)value in different variable.
$startDate = new DateTime('2014-12-31');
$endDate = clone $startDate;
$endDate->modify('+'.$days.'days');
echo $endDate->format('Y-m-d H:i:s');
You can always use clone, too:
$datetime = clone $datetime_original;
I have a website which saves images into a database. I have successfully made a function that calculates the date that an image is added and this value is also saved into the database. I now want to calculate the date two weeks ahead from the addition date. This will show the date that the image file will cease to exist in the database.
I used the function:
$dateofaddedimage= date("d/m/Y");
This calculate thee current date of the addition of the image.
I am aware that there is the strtodate() function, but i don't think it will help.
Does anyone know how to add two weeks onto this function?
Thanks!
Add a number to time(), which is the current time stamp as seconds from the Unix Epoch.
$twoweeks = time() + (2*7*24*60*60);
$thatasdate = date("d/m/Y", $twoweeks) ;
Check out date_add and the PHP DateTime model.
From the php manual page comes this fine example:
<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
If you use this on your problem, you'd have
<?php
$dateofaddedimage = new DateTime('now'); //creates DateTime Model of today (and now)
$dateofimagedestroy = new DateTime('now'); //creates DateTime Model of today as well
$dateofimagedestroy->add(new DateInterval('P14D')); // adds 14 Days to the second date
The problem with what you are doing is that date() returns a string formatted to the date - not a proper date.
I would suggest either inserting a datetime into the database such as:
insert into yourTable (timeColumn) values (now());
This will insert the actual date. From there you can use mysql functions to add and subtract from this date.
Or using a timestamp in your code such as:
$uploadedTime=time();
From there you can either use PHP functions to add or subtract dates, or (as it is a timestamp) you can also use mysql functions to calculate what you need inside queries themselves.
In my DB I have UNIX Timestamps as due dates for jobs that need to run. On a given day or a given hour I'd like to know which jobs need to run. I have the following code to query my jobs table:
$job = Model_Job::find('first',
array(
'where' => array(
array('status_id', 1), // active
array('due_date', today)
)))
The last array is just pseudo code of course. I came up with the following code to figure out if a timestamp is today.
date('Ymd', strtotime(Date::forge(time())->get_timestamp())) == date('Ymd', strtotime($job->due_date))
How would I combine that with my query? Is there a better way then looping through the queried array?
Now, this is probably not a good way but it was the first that came to mind.
$today = strtotime('today 00:00');
You can use the date from that snippet and set a WHERE due_date > $today I'm not quite sure how to do that with your database model.
edit: This relies on that you have correct timezone settings in your php configuration.
As sebastian pointed out, this will get all future dates also, but you could simply use the same technique to get the last timestamp of the day
$todaystart = strtotime('today 00:00'));
$todayend = strtotime('today 23:59:59'));
and the use a BETWEEN operator in your SQL-query