Substruct days stored in variable from date in PHP - php

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.

Related

Laravel date changing when I update a variable

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

php strtotime() values not working as expected

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.

Adding leading zeroes to a string date in PHP

I have a string "date" which can be DD.MM.YYYY or D.M.YYYY (with or without leading zeros), it depends what a user types.
Then I use it in a condition to send another email when the day is today.
if($_POST["date"]== date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
The problem is that the mail is send when the date format DD.MM.YYYY (with leading zeros) only.
My proposed solution
As I'm not very good in PHP, I only know the solution theoretically but not how to write the code - I would spend a week trying to figure it out on my own.
What's in my mind is dividing the date into three parts (day, month, year), then checking the first two parts if there's just one digit and adding leading zeros if it's the case. I don't know how to implement that to the condition above, though. I have read a few topics about how to do this, but they were a bit more different than my case is.
You should equalize to same format d.m.Y and you can do this with strtotime and date function:
$post_date = date("d.m.Y", strtotime($_POST["date"]));
if($post_date == date("d.m.Y")){
$headers.="Bcc: another#mail.cz\r\n";
}
I changed date to $post_date for more clear. I'll try to explain difference with outputs
echo $_POST["date"]; // lets say: 8.7.2013
echo date("d.m.Y"); // 09.09.2013 > it's current day
strtotime($_POST["date"]); // 1373230800 > it's given date with unix time
$post_date = date("d.m.Y", strtotime($_POST["date"])); // 08.07.2013 > it's given date as right format
If you use date function without param, it returns as current date.
Otherwise if you use with param like date('d.m.Y', strtotime('given_date'));, it returns as given date.
$post_date = date("d.m.Y", strtotime($_POST["date"]));
At first, we converted your date string to unix with strtotime then equalized and converted format that you used in if clause.
first set date format with leading Zero
$postdate = strtotime('DD.MM.YY', $_POST['date']);
and also matching date will be in same format
$matching_date = date('DD.MM.YY', strtotime('whatever the date'));
then
if ( $postdate === $matching_date )
{
// send mail
}
Why don't you just check the length of the _POST (it can be either 8 or 10)
if (strlen($_POST["date"]) == 10) {
$headers.="Bcc: another#mail.cz\r\n";
}

how to display 4-1 as month and date in php

I Am developing a php web application. Here I have date in a variable in the format 'm/d'
$var='04/25'
I have stored this value as strtotime with in my table
$var2=strtotime($var);
Then I need to display this value as 4-25 i.e. remove 0 from 04.
If the date is 1 I need to display 1 not 01
Does anyone know this?
Use the PHP date function. In your case I would say date("n-j", $var2);
Too many ways to do this, so let's go with one of them:
ltrim( $var, '0' );
I always store timestamps, that way they can easily be used with date() function to convert them to any format I need.
$now = time();
print date("n-d",$now);
Just use date function: http://php.net/manual/en/function.date.php
echo date('n-j', $var2);
try this :
copy below code and past in test.php and after run you get the out put : 4-25
<?php
$date = "04/25";
$temp = strtotime($date);
echo date('n-j',$temp);
?>

php date time function

I want to convert this date ( 02-12-2010) mm-dd-yyyy to time format
ie
to 02-12-2010 0 hours 0 minutes and 0 seconds
i have user time and date functions but when i refresh the page its value is changing as per the time.
i need that to be fixed
also i want to convert this date (01-24-2009) to time format.
please help me
Thanks
Use the strtotime function to convert an existing date/time string into a timestamp for the date function.
$new_date = date('m-d-Y h:i:s', strtotime('02-12-2010'));
The reason that your date keeps updating with the current time is that the date() function uses the current system's timestamp by default when no second parameter is provided.
Use the date_parse_from_format () API function to transform your given format to an array. E.g.
$date = "02-12-2010";
$dateArr = date_parse_from_format("d-m-Y", $date);
Output it with something like:
$output = $dateArr['day'] . '-' . $dateArr['month'] '-' . $dateArr['year'];
You can use the strtotime function eg:
$mydate = date('m-d-Y h:i:s', strtotime('02-12-2010'));

Categories