php date() function not functioning when fed with data retrieved from xml - php

I've a php file in which I've codes like
$xml_time = $update->$node->timestamp; **//Case 1**
$time = date("c",$xml_time);
$normal_time = time(); **//Case 2**
$time = date("c",$normal_time );
The variable $xml_time is retrieved from an external xml file using simpleXML. The time is stored using the time() function at some earlier point.
The problem is that, when I call the line $time = date("c",$xml_time); (is Case 1), I get an error message saying <b>Warning</b>: date() expects parameter 2 to be long, object given in <b>C:\xampp\blah\blah\blah\ajax.php</b> on line <b>46</b><br /> but in Case 2, no error shows up.
Can anyone help me identify the problem??

try if this works:
$xml_time = (integer) $update->$node->timestamp; **//Case 1**
$time = date("c",$xml_time);
This will typecast SimpleXML object to integer.

Related

strftime returns me empty string

I have a really simple error and I don't get why stftime PHP function returns me an empty string while all seems right with the syntax and code.
I got the following code:
$next_high_tide_date = strtotime($next_high_tide_date);
// FROM '2021-05-22 00:26:00' TO (timestamp) 1621635960
$next_high_tide_date_day = strtoupper(strftime('%A %d %B', $next_high_tide_date));
// THIS RETURNS ME THE RIGHT DAY DATE
$next_high_tide_date_hour = strtoupper(strftime('%k H %M', $next_high_tide_date));
// THIS RETURNS ME AN EMPTY STRING
My $next_hight_tide_date value after the first declaration is equal to 1621643160 (timestamp).
I checked on a strftime checker online and my code is right, but in my php page, still returns me a empty string.
Anyone has an idea ?
Maybe you should use the date() function to format your timestamp.
$next_high_tide_date = "2021-05-22 00:26:00";
$next_high_tide_date = strtotime($next_high_tide_date);
$next_high_tide_date_day = strtoupper(date('l d F', $next_high_tide_date));
$next_high_tide_date_hour = strtoupper(date('H \H i', $next_high_tide_date));
try this
or use %H instead of %k
$next_high_tide_date = "2021-05-22 00:26:00";
$next_high_tide_date = strtotime($next_high_tide_date);
$next_high_tide_date_day = strtoupper(strftime('%A %d %B',$next_high_tide_date));
$next_high_tide_date_hour = strtoupper(strftime('%H H %M',$next_high_tide_date));

Problem to convert unix time to human time

I have a online controller where i want to know the uptime and last seen of my access points. for this i use the epoch convert methode to convert unix time to human readable time.
this is the code i use
// getting controller ap info //
$name=$status=$uptime=$last_seen=[];
foreach ($ligowave->result as $index => $obj) {
$name[] = $obj->name;
$status[] = $obj->status;
$uptime[] = $obj->uptime;
$last_seen[] = $obj->last_seen;
}
// time settings //
$epoch = $uptime;
$uptimetime = (new DateTime("#$epoch"))->format(' H:i:s');
$epoch = $last_seen;
$lastseendate = (new DateTime("#$epoch"))->SetTimeZone(new DateTimeZone('Europe/Amsterdam'))->format(' d-m-Y H:i:s');
if ($status == "up") {
echo $name;
echo " is up, ";
echo "uptime is:" . $uptimetime;
} else {
echo $name;
echo " is down, ";
echo "device is last seen:" . $lastseendate;
}
return array($name, $status, $epoch, $uptimetime, $lastseendate);
}
the error i am getting is:
PHP Fatal error: Uncaught Exception: DateTime::__construct(): Failed
to parse time string (#Array) at position 0 (#): Unexpected character
Please Note:
This answer is only about resolving the specific PHP error as stated on the question. For a wider answer about how to effectively write code to iterate over arrays please see Fyrye's answer.
The error you are receiving is:
PHP Fatal error: Uncaught Exception: DateTime::__construct(): Failed to parse time string (#Array) at position 0 (#): Unexpected character
What is actually wrong, and why?
1)
You have an uncaught Exception, which throws a fatal error due to being, er, uncaught. Exceptions are central to object programming and should be researched and implemented in your PHP scripts.
2)
Why do you have an Exception in the first place? The error states the exception is caused by "Failed to parse time string (#Array)". So you are trying to give the DateTime object an array when it expects a string. It would help you to Read the PHP DateTime __construct Manual Page.
3)
Further, and more specifically the # character is unexpected; which means it should not be there. This character is only valid when followed by timestamp integer values in string format.
Because the array is output as a string (i.e in quotes) the end result is "#Array" and so the # is taken literally by DateTime; but of course this character is not expected by DateTime in any non-numeric incoming time string. This is the root cause of your fatal error here.
While PHP does employ loose typecasting to some extent, wrapping an array $var in quotes is far too loose and so the array simply outputs "Array" and issues a corresponding PHP Notice:
Notice: Array to string conversion in .....
For a valid list of correct DateTime string formats to give the object you can view this page from the PHP Manual.
4)
I do not see why you need those outer brackets?
So, how should this be done?
Reading the issues in reverse order from 4 to 1; the correct way of resolving this specific error is:
Wrap the attempt into a try/catch block to avoid these fatal errors.
Ensure that the value given to the DateTime object is a string
Remove unnecessary and invalid characters from that string.
So:
$epoch = $uptime;
try{
/***
* Uptime appears to be a numeric array of time string values
* Therefore go for the first one.
* You may want to wrap this code in a loop to catch each one.
***/
$uptimeTime = new DateTime("#".(string)$epoch[0]);
}
catch (Exception $ex){
/***
* If you wish to ignore these errors simply leave this block empty
***/
error_log("There was a problem on line ".__LINE__."! ".print_r($ex));
}
/***
* By default UTC timestamps are not zoned.
***/
// $uptimeTime->setTimeZone(new DateTimeZone('Europe/Amsterdam'));
$uptimeTimeOutput = $uptimeTime->format('H:i:s');
/***
* $uptimeTimeOutput is the correctly formatted date from $epoch[0]
***/
print $uptimeTimeOutput;
I hope with the information given above your able to correct the second DateTime instantiation code (ie the new DateTime line) yourself. :-)
TL;DR
Please read the PHP Manual and allow it to inform your coding choices.
The main issue is caused by defining $uptime[] as an array of values, resulting in $epoch = $uptime containing an array of timestamp strings. When DateTime() expects a single string value.
To resolve the issue you need to move the DateTime calls inside of the foreach iteration.
The other issue, as mentioned in the answer provided by Martin, is that you are not handling exceptions within your code. If uptime or last_seen is not of an expected value that is being supplied to the DateTime constructor, an exception will be thrown.
To handle the exceptions you can use atry/catch block in order to handle an issue that arises in your code. Exceptions are meant to point you to fatal errors in your code so that you can resolve or verify them programmatically and typically should not be ignored by using try/catch. For more details please see https://www.php.net/manual/en/language.exceptions.php
Without knowing exactly what you're trying to accomplish with your code. It appears you are wanting to echo and return all of the values from $ligowave->result. I made the appropriate changes below to reflect what I surmise are your intentions. Along with some minor simplifications.
Please clarify what you are wanting to return and echo and I will adjust my answer.
Example: https://3v4l.org/O0nS6
//...
// getting controller ap info //
$values = [];
foreach ($ligowave->result as $index => $obj) {
//convert the unix timestamps to DateTime objects
$uptime = (new DateTime('#' . $obj->uptime));
$last_seen = (new DateTime('#' . $obj->last_seen))->setTimeZone(new DateTimeZone('Europe/Amsterdam'));
//store the return values into an array
$values[] = $value = [
'name' => $obj->name,
'status' => $obj->status,
'uptimetime' => $uptime->format('H:i:s'),
'lastseendate' => $last_seen->format('d-m-Y H:i:s')
];
//output each of the statuses
printf('%s is %s, ', $obj->name, $obj->status);
if ('up' === $obj->status) {
echo 'uptime is: ' . $value['uptimetime'];
} else {
echo 'device is last seen: ' . $value['lastseendate'];
}
}
return $values;
}
Result:
foo is up, uptime is: 10:20:54
bar is down, device is last seen: 01-06-2019 08:22:30
Returns:
array (
0 =>
array (
'name' => 'foo',
'status' => 'up',
'uptimetime' => '10:20:54',
'lastseendate' => '05-06-2019 11:16:21',
),
1 =>
array (
'name' => 'bar',
'status' => 'down',
'uptimetime' => '10:20:54',
'lastseendate' => '01-06-2019 08:22:30',
),
)
It also appears that you are using a 24 hour time, to represent a duration.
If so you will need to use a DateInterval instead of DateTime, by using DateTime::diff from an appropriate timeframe. For more details please see https://php.net/manual/en/class.dateinterval.php
Assuming uptime is the started time and last_seen is the current run time, you can use $uptime->diff($last_seen), to retrieve the time that elapsed between uptime to last_seen (duration), instead of the 24 hour time value of uptime. Otherwise you can use $uptime->diff(new DateTime('now', new DateTimeZone('Europe/Amsterdam'))), to use the current date time.
One caveat, is that the hours of DateInterval are non cumulative, meaning you would need to add the days in some manner. I have used the most accurate of %a as opposed to adding on to the hours with days * 24
Example: https://3v4l.org/LHdqL
//...
$uptime = (new DateTime('#' . $obj->uptime))->setTimeZone(new DateTimeZone('Europe/Amsterdam'));
$last_seen = (new DateTime('#' . $obj->last_seen))->setTimeZone(new DateTimeZone('Europe/Amsterdam'));
$values[] = $value = [
'name' => $obj->name,
'status' => $obj->status,
'lastseendate' => $last_seen->format('d-m-Y H:i:s'),
'uptimetime' => $uptime->diff($last_seen)->format('%a.%H:%I:%S'), //DD.HH:MM:SS
];
//...
Result:
foo is up, uptime is: 12.22:48:26

Php, date_modify() with a variable

I need to use the indexed element as the amount to change the date by
$id = $_POST['id'];
$ids = explode(',',$id);
$dateCreated = date('Y-m-d');
$dateExpiredtemp =date_create($dateCreated);
date_modify($dateExpiredtemp,'+ $ids[2]');
$dateExpired = date('$dateExpiredtemp');
date_modify($dateExpiredtemp,'+ $ids[2]');
This line provides this error
Warning: date_modify(): Failed to parse time string (+ $ids[2]) at position 0 (+): Unexpected character in
$ids[2] is a string and it needs to be carried into the altering parameter of date_modify
Change this line of code
date_modify($dateExpiredtemp,'+ $ids[2]');
into
date_modify($dateExpiredtemp,'+ ' . $ids[2]);
Your initial code will not recognize the $ids[2] since it is included in the string. Therefore, $ids[2] won't be parsed.
There seems to be something wrong with your $ids array.
I assume that $ids[2] is just a number and that is why you're getting an error. You need to specify a unit of time such as days. Take a look at the code below, I have added days to the end of the 2nd parameter in the date_modify function.
$id = $_POST['id'];
$ids = explode(',',$id);
$dateCreated = date('Y-m-d');
$dateExpiredtemp =date_create($dateCreated);
date_modify($dateExpiredtemp,'+ $ids[2] days');
$dateExpired = date('$dateExpiredtemp');

PHP Input Error- String to Time Input [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 3 years ago.
I'm trying to receive data from input that I changed from "text" to the "time" selector. Now when the data goes in, it's generating the following error listed below. I understand why this is happening, but don't know where and how to change the code so that the code can process the PHP "time" input.
Error:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (013:59) at position 0 (0): Unexpected character' in C:\xampp\htdocs\index.php:240 Stack trace: #0 C:\xampp\htdocs\index.php(240): DateTime->__construct('013:59') #1 C:\xampp\htdocs\index.php(84): format_time('13:59') #2 {main} thrown in C:\xampp\htdocs\index.php on line 240
Relevant Code:
if($to){
$s = (int)format_time($start);
$e = (int)format_time($end);
function ct($time){
$timezone_offset = 14400000; //EST vs UTC in ms
return new MongoDB\BSON\UTCDateTime(strtotime($time)*1000 + $timezone_offset);
}
function now_in_mongo($offset = 0){
return new MongoDB\BSON\UTCDateTime(time()*1000 + $offset*1000);
}
function format_time($time){
if(strlen($time) != 6){
$time = "0$time";
}
$date = new DateTime($time);
$date->add(new DateInterval('PT4H'));
return $date->format('His');
}
I am not sure why you are checking the input for length under 6. A correct time input would have length of 5 (e.g 12:34), so at least you should use
if(strlen($time) != 5)
However this also may not always be correct - yet I'm not sure how you are constructing your $time string.
I think your time format should be like this xx:xx, i didnt tried your code but you can check the string to parse using a regex '/^\d{2}:\d{2}$/'
And use DateTime::CreateFromFormat to create ur date object.

PHP print_r writes variable mystery?

I'm running into some very strange behavior with php in a webclient I'm working on. Essentially I'm passing an expiration date as a string which I'm parsing into a DateTime so I can compare it to the current time (to ascertain if something has expired or not.)
Heres the code snippet in question (NOTE: $expiration is set above this snippet, I'm just rewriting over it with the value I actually intend on using)
$expiration = DateTime::createFromFormat("y-m-d h:i:s", $expiration);
$now = date('y-m-d h:i:s', time());
Common::log("before : ", $expiration->date);
//TODO figure out why this common log has to be here or this doesnt work
Common::log("expiration : ", $expiration);
Common::log("after : ", $expiration->date);
if($now > $expiration->date) $data['status'] = 14;
Common::log is an in house function which is just doing print_r
static function log ($msg, $data=null)
{
error_log ($msg . ($data ? print_r ($data, true) : ''));
}
What that code snippet puts out into terminal (which is where I'm looking at whats getting print) is the following.
[09-Jun-2015 17:03:19 America/Indiana/Indianapolis] before :
[09-Jun-2015 17:03:19 America/Indiana/Indianapolis] expiration : DateTime Object
(
[date] => 2015-06-09 06:16:55
[timezone_type] => 3
[timezone] => America/Indiana/Indianapolis
)
[09-Jun-2015 17:03:19 America/Indiana/Indianapolis] after : 2015-06-09 06:16:55
if I simply comment out or delete the line thats logging the $expiration variable then, as the before : log shows, $expiration->date evaluates to the empty string and my logic doing the comparison below breaks. Whats going on here, why does taking out that middle log have any impact on the value of $expiration->date? This is extremely perplexing, and I would appreciate any help anyone can offer on this - I don't want to use code that works if I don't understand why it works.
To be honest I am not sure why this is happening. It probably has something to do with the class constructor. However, there is no documentation for using ->date this way. So, instead of doing things like this:
Common::log("before : ", $expiration->date);
do things this way:
Common::log("before : ", $expiration->format('y-m-d h:i:s'));
In other words you are telling PHP to display the date in the output format you choose (which could be different from the input format that you created it with).

Categories