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
Related
As the title says I am trying to subtract a number of days (stored in variable) from a date. I am using the date_sub function.
This is the variable which contains the days that I want to substract (integer from a field)
$days=$rowRate['days'];
The function:
$chargedate=date_sub($arrivaldate,date_interval_create_from_date_string($days."days"));
$arrivaldate is the variable that contains the date that i want to substract the $days from.
When I use it, I get the warning date_sub() expects parameter 1 to be DateTime, string given in :\xampp\htdocs\Project\file.php on line 55.
I think I am messing up with the concatenation but I can not figure this out. Any help would be appreciated.
Try converting the $arrivaldate variable like this before passing it into the date_sub function:
$arrivaldate = date('Y-M-D', strtotime($arrivaldate));
$chargedate=date_sub(
$arrivaldate,
date_interval_create_from_date_string($days."days")
);
Per the error message you need to create a DateTime object from the $arrivaldate before calling date_sub:
$date = date_create(date('Y-m-d', strtotime($arrivaldate)));
$chargedate = date_sub($date,date_interval_create_from_date_string($days." days"));
echo date_format($chargedate, "Y-m-d");
I added the strtotime because it's not clear what format you are using but it may not be necessary.
The date_sub and date_add functions are only used in practice if a DateInteval is already available. Your task can be solved more efficiently and easily with DateTime::modify().
$arrivaldate = "2021-08-16";
$days = "5"; //may be also integer
$startDate = date_create($arrivaldate)->modify(-$days."Days");
//test output: 11/08/2021
echo $startDate->format("d/m/Y");
Important: The date in $arrivaldate must have a format wich accepted from DateTime.
What is the "cleanest" way to add a date and a time string in PHP?
Albeit having read that DateTime::add expects a DateInterval, I tried
$date = new \DateTime('17.03.2016');
$time = new \DateTime('20:20');
$result = $date->add($time);
Which was no good and returned nothing to $result.
To make a DateInterval from '20:20', I only found very complex solutions...
Maybe I should use timestamps?
$date = strtotime($datestring);
$timeObj = new \DateTime($timestring);
// quirk to only get time in seconds from string date
$time = $timeObj->format('H') * 3600 + $timeObj->format('i') * 60 + $timeObj->format('s');
$datetime = $date+$time;
$result = new \DateTime;
$result->setTimestamp($datetime);
In my case, this returns the desired result, with the correct timezone offset. But what do you think, is this robust? Is there a better way?
If you want to add 20 hours and 20 minutes to a DateTime:
$date = new \DateTime('17.03.2016');
$date->add($new \DateInterval('PT20H20M'));
You do not need to get the result of add(), calling add() on a DateTime object will change it. The return value of add() is the DateTime object itself so you can chain methods.
See DateInterval::__construct to see how to set the intervals.
DateTime (and DateTimeImmutable) has a modify method which you could leverage to modify the time by adding 20 hours and 20 minutes.
Updated
I've included examples for both DateTime and DateTimeImmutable as per the comment made, you don't need to assign the outcome of modify to a variable because it mutates the original object. Whereas DateTimeImmutable creates a new instance and doesn't mutate the original object.
DateTime
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
echo $start->modify('+20 hours +20 minutes')->format('Y-m-d H:i:s');
// 2018-10-23 20:20:00
Using DateTime: https://3v4l.org/6eon8
DateTimeImmutable
<?php
$start = new DateTimeImmutable('2018-10-23 00:00:00');
$datetime = $start->modify('+20 hours +20 minutes');
var_dump($start->format('Y-m-d H:i:s'));
var_dump($datetime->format('Y-m-d H:i:s'));
Output
string(19) "2018-10-23 00:00:00"
string(19) "2018-10-23 20:20:00"
Using DateTimeImmutable: https://3v4l.org/oRehh
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'm trying to use 'whereBetween' eloqouent query with two given start and end dates.
$first_day_this_month = date('Y-m-01 H:s:i'); //get the first day of the current month
$yesterDay = date('Y-m-d H:s:i',strtotime("-1 days")); //get yesterday's date
$d = m_chat_history::where('employee_id',$request->other_id)
->whereNull('to_group')->where('to_employee_id',$request->id)
->whereBetween('created_at',[$yesterDay,$first_day_this_month])
->get();
I make sure I have all the required data for the query by 'var_dump' and it did gives me all the required data needed for the query but the query returns me an empty output. Any ideas, clues, suggestions, help, recommendations please? I tried to remove the 'whereBetween' and my query works like it returns me the expected output but with 'whereBetween', the return output is empty.
Make sure to use the same type and format as created_at when defining the values for whereBetween. As you're using datetime you could define edge values like (just one of many ways of doing it):
$first_day_this_month = date('Y-m-01 H:i:s');
$yesterday = date('Y-m-d H:i:s', strtotime("-1 day"));
Also make sure of the order of params (still please consider edge cases like first day of the month where $yesterday would be smaller, so you have to add some logic and be careful):
->whereBetween('created_at', [$first_day_this_month, $yesterday])
Edit: wasn't timestamp...
Try this,
but first you have to install Carbon with composer.
after doing that
use Carbon
then write the fallowing code
$yesterday = Carbon::yesterday()->toDateTimeString();
$carbon = new Carbon('first day of ' . date('F Y'));
$first_day = $carbon->toDateTimeString();
and in your query
->whereBetween('created_at', [$first_day, $yesterday])
I' am trying to convert the date of next 7 days into timestamp so that I can compare against my date timestamp in database to get some results.
This function is used to get the next 7 days from today
$next_date = date("d/m/Y", strtotime("7 day"))
Output
30/04/2014
Now I' am again running strtotime() on $next_date variable who holds the next 7days and converting to timestamp.
echo strtotime($next_date);
This is not working. I followed this stackoverflow answer and few others.
As an alternative suggestion you could look at PHP's internal DateTime() and DateInterval() classes. It makes it a bit easier to convert between formats and do date/time addition and subtraction imho. DateInterval requires at least PHP version 5.3.
An example:
// create a current DateTime
$currDate = new DateTime();
// copy the current DateTime and
// add an interval of 7 days
$nextDate = clone $currDate;
$nextDate->add(new DateInterval('P7D'));
// both objects are easily converted to timestamps
echo $currDate->getTimestamp(); // e.g: 1398296728
echo $nextDate->getTimestamp(); // e.g: 1398901528
// and both can be easily formatted in other formats
echo $currDate->format('d/m/Y'); // e.g: 24/04/2014
echo $nextDate->format('d/m/Y'); // e.g: 01/05/2014
EDIT
For completeness, here's another example of how you can add seven days to a DateTime object:
$now = new DateTimeImmutable();
$then = $now->modify('+7 days');
var_dump($now->format('Y-m-d'), $then->format('Y-m-d'));
Yields:
string(10) "2016-05-24"
string(10) "2016-05-31"
You can also use DateTime - the difference in this use case is that DateTime::modify() will modify the instance $now where DateTimeImmutable::modify() will return a new DateTimeImmutable object - so if you need to create a new object whilst retaining the old one, it's probably the most succinct approach.
Hope this helps :)
http://www.php.net/manual/en/datetime.construct.php
http://www.php.net/manual/en/dateinterval.construct.php
Just store the value from strtotime first?
$timestamp_in_7_days = strtotime('7 day');
$next_date = date('d/m/Y', $timestamp_in_7_days);
There is no need to throw the time back and forth between unix timestamp and date-format.