Added Namespace and lost all the PHP OOPs Classes

If you leave that to PHP’s date extension (as shown in post #19) you don’t need to remember when the DST is. And it’s much less code.

1 Like

I did try your script with the JSON “time” and it failed with an obscure error message instead of returning an object:

$json_datetime = '2018-11-02T13:15:37.346992742Z';
$datetime      = new DateTimeImmutable($json_datetime);
..
..

The prettified error message returned:

Fatal error: Uncaught Exception:
DateTimeImmutable::__construct():
Failed to parse time string (2018-11-02T13:15:37.346992742Z) at position 0 (2):
The timezone could not be found in the database in /…/…/incs/latest.php:67

Stack trace: #0 /…/…/…/incs/latest.php(67):
DateTimeImmutable->__construct(‘2018-11-02T13:1…’)
#1 {main} thrown in /…/…/…/incs/latest.php on line 67

I did not understand the error message, had lots of other niggly problems to solve because I moved the script to another URL so continued with the script that worked.

I have since solved most of the other niggly problems, returned, tested and discovered $json_datetime; parameter must conform to a certain structure. The supplied JSON parameter had an extra character preceding the trailing Z. Removing the extra character and your script worked fine.

Many thanks :slight_smile:

It basically says that the default timezone your PHP installation uses is garbage.

  • check what timezone is set in php.ini
  • if there is none, set either your local timezone or UTC
  • if there is something set that doesn’t make sense, correct

Unfortunately the problem was inconsistent and not easy to pinpoint.

The following online sample of ten test results show how some Sensor Device_id intermittently return the correct results:

I did find this post which I think maybe the problem.

https://secure.php.net/manual/en/datetime.createfromformat.php

The Workaround:

Truncate the trailing milliseconds because they are not required:

  // $row->time = '2018-10-27T08:36:25.356781773Z';	 

  $json_datetime = strstr($row->time, '.', true); // remove milliseconds
  
  // Result:
  /*
	$row->time ==> 2018-10-27T08:36:25.356781773Z

	$json_datetime ==> 2018-10-27T08:36:25

    DateTimeImmutable Object
    (
        [date] => 2018-10-27 08:36:25.000000
        [timezone_type] => 3
        [timezone] => Asia/Bangkok
    )
  */	

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.