Date POST switching types - php

I don't know really how to elaborate on this problem. I have the following markup in my form:
<input class="form-control" type="date" name="renewal" required="required" id="renewal" />
and if I call var_dump it tells me that it is a String value of the date formatted in a Y-m-d format. However, if I attempt to convert the String to a DateTime object using the following:
$_POST['renewal'] = new DateTime($_POST['renewal']);
I get the following error message:
Fatal error: Uncaught TypeError: DateTime::__construct() expects parameter 1 to be string, object given in *.php:212 Stack trace: #0 *.php(212): DateTime->__construct(Object(DateTime)) #1 {main} thrown in *.php on line 212
So if I try to explicitly convert $_POST['renewal'] to a String using strval:
$_POST['renewal'] = new DateTime(strval($_POST['renewal']));
I receive the following error:
Recoverable fatal error: Object of class DateTime could not be converted to string in *.php on line 212
And if I try to get the format from $_POST['renewal'] using:
$_POST['renewal'] = new DateTime($_POST['renewal']->format('Y-m-d'));
I receive the following error:
Fatal error: Uncaught Error: Call to a member function format() on string in *.php:212 Stack trace: #0 {main} thrown in *.php on line 212
And if I try to not do anything to the POST value and try to set the date's year to this year's value using the following:
$_POST['renewal'] = new DateTime($today->format('Y') . $_POST['renewal']->format('-m-d'));
I receive the same call to a member function error as shown above. So why does it tell me when I attempt to convert the POST value to a DateTime object that it expects a String and not a DateTime object, but whenever I try to use the value as a DateTime object it says that the object is a String?
UPDATE
To show you what I'm trying to do, I am trying to see if the value of $_POST['renewal'] is greater than today's date. If the value of the POST greater than today's date then I'm changing the value to today's year and if the value is still not greater than today's date then I'm also adding 6 month's to the date. Here is the code that I'm trying to use:
$today = new DateTime("now");
$_POST['renewal'] = new DateTime($_POST['renewal']->format('Y-m-d'));
if ($_POST['renewal'] < $today) {
$_POST['renewal'] = new DateTime($today->format('Y') . $_POST['renewal']->format('-m-d'));
if ($_POST['renewal'] < $today) {
date_add($_POST['renewal'], date_interval_create_from_date_string('6 months'));
}
}
The value that I'm using to test the code is 2016-06-28, and what I expect it to do is change to 2018-06-28 and then again to 2018-12-28. But if I send the value of 2017-11-01 then it would change to 2018-11-01 and if I send the value of 2018-12-01 then it would not change at all.

Related

PHP date function causes problems if input value is empty

I am using the following PHP code to get the upcoming date of a given day.
For example If the day given in "Tuesday" it will output 01-09-2020.
The function is to show upcoming sale dates of smartphones.
$saledate = "Tuesday"
date_default_timezone_set('Asia/Kolkata');
function dayDate($day) {
return new DateTime('next ' . $day);
}
$nextsale = dayDate($saledate);
if(!empty($saledate)) {
echo "Next Flash Sale on $saledate ";
echo $nextsale->format('d-m-Y'); // 01-09-2020
}
The problem is if the $saledate is empty, it causes the entire web page to not load. What could be the issue ?
This is what the errorlog says
[25-Aug-2020 18:47:15 Asia/Kolkata] PHP Fatal error: Uncaught Error: Call to undefined function dayDate() in /home/customer/www/sitename.com/public_html/index.php:1114
Stack trace:
#0 {main}
thrown in /home/customer/www/sitename.com/public_html/index.php on line 1114
Update: Fixed by adding the $nextsale = dayDate($saledate); inside the if block.

PHP - DateTime->add not working. Says DateInterval format is wrong

I've been struggling for a few hours on an error that I'm sure it's silly, but I can't find to solve it.
My idea is to create a DateTime of (00:00:00), in order to add to it in a loop 4:30 hours per $i.
$saldo_funcionario = new DateTime('00:00:00');
for ($i=0; $i<$value; $i++) {
$tempo_dia_funcionario = new DateInterval('PT4H30I');
$saldo_funcionario->add($tempo_dia_funcionario);
}
The error message is:
Fatal error: Uncaught exception 'Exception' with message 'DateInterval::__construct(): Unknown or bad format (PT4H30I)'
DateInterval->__construct('PT4H30I') #1 {main} on line 75
Where am I missing?
$tempo_dia_funcionario = new DateInterval('PT4H30I');
Should be:
$tempo_dia_funcionario = new DateInterval('PT4H30M');
Notice 'M' instead of 'I'.
http://php.net/manual/en/dateinterval.construct.php

PHP Date create From Format inside a function/non object error

I have the following code producing this error: Fatal error: Call to a member function setTimeZone() on a non-object in C:\wamp\www\grid2.php on line 58
I am trying to set up this function to take in a date string as below, apply the time offset, then output it back out in the format set up in the function call... but no luck.
<?php
if (!session_id()) session_start();
$_SESSION["timeoffset"] = "Europe/Amsterdam";
function formatDate($date, $format){
// use the the appropriate timezone for your stamp
$timestamp = DateTime::createFromFormat($format, $date, new DateTimeZone('UTC'));
// set it to whatever you want to convert it
$timestamp->setTimeZone(new DateTimeZone($_SESSION["timeoffset"]));
echo $timestamp->format($format);
}
formatDate('2012-10-14T21:15', 'Y-m-d\TH:i');
?>
I am also trying to figure out how return the string with a certain number of added minutes amount of minutes.
So the string "2012-10-14T21:15" would have 5 minutes added = "2012-10-14T21:20"
Any help would be greatly appreciated!
Jeff
DateTime::createFromFormat will return false on failure. This means that:
DateTime::createFromFormat($format, $date, new DateTimeZone('UTC'));
has failed and that $timestamp is false (var_dump($timestamp) will show you). Without knowing what you're passing in as your parameters for function formatDate, I don't think anyone will be able to figure out exactly what you're doing wrong.
Use this rather
$timestamp->setTimeZone(new DateTimeZone("Europe/Amsterdam"));
I think the sessions array isn't returning the string Europe/Amsterdam.
Do the debugging

Cannot save a DateTime object to a datetime field in MySQL

Here is my database schema for my MySQL database:
create table noticia
(
id int,
imagen varchar(255),
fecha datetime,
titulo varchar(255),
url varchar(255),
descripcion varchar(255),
contenido text
)
I'm using RedBeanPHP as my ORM to save the information to a database. Here is where I'm scraping and parsing the dates to a DateTime object as per the documentation.
foreach ($element->find('span.fechanoticia') as $fecha) {
$tmp = str_replace("/", "-", $fecha->innertext);
print_r($tmp);
$dateFoo = new DateTime($tmp);
echo $dateFoo->format('Y-m-d H:i:s');
$newItem->set_fechanoticia($dateFoo);
}
The $tmp variable this value for example:
05-09-2012
The echo call to format returns:
2012-09-05 00:00:00
Everything is peachy, and working.
However when I try to save it to the database using RedBeanPHP I get this error:
Fatal error: Uncaught exception 'RedBean_Exception_Security' with
message 'Invalid Bean: property fecha ' in
C:\xampp\htdocs\blog-uvm\rb.php:4880 Stack trace: #0
C:\xampp\htdocs\blog-uvm\rb.php(5108):
RedBean_OODB->check(Object(RedBean_OODBBean)) #1
C:\xampp\htdocs\blog-uvm\rb.php(5082):
RedBean_OODB->storeBean(Object(RedBean_OODBBean)) #2
C:\xampp\htdocs\blog-uvm\rb.php(7005):
RedBean_OODB->store(Object(RedBean_OODBBean)) #3
C:\xampp\htdocs\blog-uvm\index.php(60):
RedBean_Facade::store(Object(RedBean_OODBBean)) #4 {main} thrown in
C:\xampp\htdocs\blog-uvm\rb.php on line 4880
Can RedBeanPHP not handle datetime objects?
As per RedBean's documentation (More data types), you can only save DateTime objects if they are in string form.
For example:
// It's a string - not a DateTime.
$photo->created = '1995-12-05 19:00:00';
In this case the solution should be to save the formatted string, not the DateTime object itself:
$newItem->set_fechanoticia($dateFoo->format('Y-m-d H:i:s'));
found this: http://groups.google.com/group/redbeanorm/browse_thread/thread/6961ac635e6886f6
The Optimizer will now convert columns with datetime values to datetimefields. If a different value is inserted the column will be reverted by OODB in fluid mode.

datetime datatype not working in soap php

This is my code
$c = new soapclient('http://www.redbus.in/WS2/BookingService.asmx?wsdl',
array('authentication' => array('LoginID' => 'x','Password'=>'x')));
$timezone = new DateTimeZone('UTC');
$time='2012-04-17T16:50:45';
$date = new DateTime($time,$timezone);
$sourceid=array('SourceID'=>'244','DestinationID'=>'477','DateOfJourney' =>$date);
$stockprice = $c->GetAvailableRoutes($sourceid);
print_r($stockprint);
it's not working in datetime format datatype variable
it shows error like this
Fatal error: Uncaught SoapFault exception: [soap:Client] Server was unable to read request. ---> There is an error in XML document (2, 252). ---> The string '' is not a valid AllXsd value. in E:\xampplite\htdocs\index1.php:9 Stack trace: #0 [internal function]: SoapClient->__call('GetAvailableRou...', Array) #1 E:\xampplite\htdocs\index1.php(9): SoapClient->GetAvailableRoutes(Array) #2 {main} thrown in E:\xampplite\htdocs\index1.php on line 9
I had a similar problem when using a SOAP service from PHP. I fixed it using:
$date->format('c');
(ISO 8601 date, added in PHP 5, looks like: 2004-02-12T15:19:21+00:00)
You need to format it, otherwise you are throwing an DateTime object into your array (which PHP tries to convert to a string, which does not work)
For example:
$date->format('Y.m.d H:i:s');
Usage
$sourceid = array('SourceID'=>'244','DestinationID'=>'477','DateOfJourney' => $date->format('Y.m.d H:i:s'));

Categories