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
Related
I'm writing a scope query and I'm passing in a fetch_date to pull things from the DB table based on the created_at timestamp.
I'm trying to find all records for a month, but the variable $fetch_date keeps changing whenever I try the following:
//$fetch_date is a carbon instance and is equal to the month the user selected
//ie: Carbon {#221 ▼
// +"date": "2016-07-01 00:00:00.000000"
//Create the next_month
$next_month = $fetch_date->addMonth();
//Format next_month as a string
$next_month = $next_month->format('Y-m-d');
//Format fetch_date as a string
$fetch_date = $fetch_date->format('Y-m-d');
dd($fetch_date);
//This now gives me 2016-08-01 - why?
Why does the fetch_date change? I'm essentially trying to keep the $fetch_date as the current month and the $next_month to simply be the start of the next month.
I'm guessing there's a real simple reason to this I'm just overlooking.
Because calling the addMonth method has side effects.
If you look at Carbon's source, you'll see that all addMonth is doing is calling addMonths with a value of 1, which in turn is simply calling DateTime::modify. It's not explicitly spelled out in the documentation, but from the examples it's pretty plain that calling the method modifies the stored time value:
Example #1 DateTime::modify() example
<?php
$date = new DateTime('2006-12-12');
$date->modify('+1 day');
echo $date->format('Y-m-d');
?>
To avoid this, keep a copy of of the time around and modify that:
$also_fetch_date = clone $fetch_date;
$next_month = $also_fetch_date->addMonth();
// ...
Seems you are adding a month to the fetch_date variable.
Try this:
$next_month = Carbon::createFromFormat('Y-m-d', $fetch_date->format('Y-m-d'));
$next_month->addMonth();
dd($next_month->format('Y-m-d'));
Take a look at the documentation of Carbon: http://carbon.nesbot.com/docs/
Maybe will help you
I use a timepicker to get a time string(eg: '1:00am' or '12:00pm'). I need to modify and store this in a mysql TIME data type column as eg: '12:00:00'. Now, since the TIME column stores in 24 hrs format, I need to "modify" it. I can't seem to find any help to modify using Carbon, since I'm not using any dates. I'm using a mutator in Laravel, but would like to know if there is a better way like using Carbon for dates.
public function setTimeAttribute($time) {
if(substr($time, -2, 0) == 'am') {
// do nothing
} else if(substr($time, -2, 0) == 'pm') {
// increase hours.ie: 1:00pm to 13:00:00
}
}
Any help would be appreciated! Thanks.
Use PHP strtotime() function.
$time = "12:00am";
$timestamp = strtotime($time);
echo $timestamp;
//Will print something like: 1469228400
Or any other date format you prefer.
It's best to store time as timestamp, to convert it back you can use date() function.
E.g: $value = date("H:i:s", $timestamp);
I have trouble with Carbon's between function. It is giving me a false although I am expecting a true. Here is my code
$now=Carbon::now();
$updated_at=$checkup->updated_at;
if($updated_at->between($now->subMonths($program->months_since_checkup),$now))
//$program->months_since_checkup returns the number 12.
Any thoughts?
P.S. let me add that updated_at is March 23,2016 and is pulled as a carbon object too.
When you type this
$now->subMonths($program->months_since_checkup)
It will subtract 12 months of your variable $now modifying it.
To solve this try to separate these two variables:
$first = Carbon::now();
$second = Carbon::now()->subMonths($program->months_since_checkup);
if ($updated_at->between($first, $second)) {
this code keeps telling me that $lasUpdate is always greater than $yesterday no matter the change i make to $yesterday result is (12/31/14 is greater than 01/19/15 no update needed). i feel like i'm missing something simple thank you in advance it is greatly appreciated.
$result['MAX(Date)']='12/31/14';
$lastUpdate = date('m/d/y', strtotime($result['MAX(Date)']));
$yesterday = date('m/d/y', strtotime('-1 day'));
if($lastUpdate<$yesterday){echo $lastUpdate.'is less '.$yesterday.'<br>'.'update needed';}
if($lastUpdate>=$yesterday){echo $lastUpdate.'is greater than '.$yesterday.'<br>'.'no update needed';
You have fallen victim to PHP type juggling with strings. A date function has a return value of a string. You cannot compare dates in their string format since PHP will juggle strings into integers in the context of a comparison. The only exception is if the string is a valid number. In essence, you are doing:
if ('12/31/14' < '01/19/15') { ... }
if ('12/31/14' >= '01/19/15') { ... }
Which PHP type juggles to:
if (12 < 1) { ... }
if (12 >= 1) { ... }
And returns false on the first instance, and true on the second instance.
Your solution is to not wrap date around the strtotime functions, and just use the returned timestamps from the strtotime functions themselves to compare UNIX timestamps directly:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
You will however want to use date when you do the echo back to the user so they have a meaningful date string to work with.
Try something like this:
$lastUpdate = strtotime($result['MAX(Date)']);
$yesterday = strtotime('-1 day');
if ($lastUpdate < $yesterday) { /* do Something */ }
12/31/14 is greater than 01/19/15
Because 1 is greater than 0. If you want to compare dates that way you will need to store them in a different format (from most to least significant digit), for example Ymd.
Or store the timestamps you are making in the different variables and compare them.
The first date is today's date and the second one is being retrieved from a DB. The purpose of what I'm trying to do is that I want to trigger an alert 7 days before the due date, which is the date stored in the DB.
I have tried to figure this out a few different ways without any success. I started by using the strtotime function to subtract days from the retrieved date and then compare it to today's date. Here is my first try:
$date1 = strtotime(date('2013-11-14',strtotime('-7 days')));
$date2 = strtotime(date('Y-m-d'));
$check = $date1 - $date2;
$check = date('j',$check);
if($check <= 7){echo "Under 1 week";}
But that doesn't work because it doesn't take into account the month, only the day...so 2013-12-14 will return the same result as 2013-11-13.
So then I tried:
$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('now');
$interval = $datetime1->diff($datetime2);
$interval->format('%a');
if($interval <= 7){echo "Under 1 week";}
But then I get an error:
*Object of class DateInterval could not be converted to int*
I figured that a number was an integer no matter what, but I've now learned that isn't the case.
I have done a lot of searching on the internet, because I'm sure someone else has been trying to do this same thing and I found this helpful bit of code that works perfectly:
function e_days($end,$start) {
/************************************************************************/
/* Purpose: To get the elapsed days of date diff as integer. */
/************************************************************************/
$dtS = new DateTime($start);
$dtE = new DateTime($end);
$int = $dtE->diff($dtS);
$ret = (integer) $int->format('%a');
return $ret;
} // end function
Normally I would just carry on and be happy, but I don't like to just use something I found without understanding it. The part I don't understand is this line:
$ret = (integer) $int->format('%a');
What is "(integer)" ? I assume it must change the number to an integer but I can't find it on php.net listed as a function.
I would also like to know if there is another way to do this, or if this guy nailed it.
Function Credit: OldManRiver
(integer) casts whatever immediate follows it as an int type. In your case, it casts $int->format('%a') into an integer.
Consider the following (int is an alias for integer):
$str = "10";
$num = (int)$str;
if ($str === 10) echo "String";
if ($num === 10) echo "Integer";
In the example above, $int = $dtE->diff($dtS), so int is the difference between two DateTime objects in DateTime format. According to the documentation, format('%a') returns the total number of days between the two objects. Casting the return value using (integer) ensures that it will be an int type.
UPDATE:
More info on type-casting can be found here (for integers) and here (for general "type juggling").
From the docs:
To explicitly convert a value to integer, use either the (int) or (integer) casts.
(int), (integer) - cast to integer