0

I am using cakephp4 and a Xero API. I can't find the code to convert a date returned as '/Date(1617667200000+0000)/' from a Xero API. It is a timestamp with the first 10 digits eg the $rr=gmdate("Y-m-d", 1617667200); will work but I can't hardcode strings like this or just find the first 10 digits. It's a StringUtil I believe. I tried using JSON date examples as well but not getting anywhere including Xero docs.

 $rr=StringUtil::convertStringToDate($date);//no
 $rr=gmdate("Y-m-d", $date);  //no

Converting json results to a date

ndm
  • 59,784
  • 9
  • 71
  • 110
atown99
  • 109
  • 12
  • it seems to me like it's generated in milliseconds so timestamp `1617667200000` should be divided by 1000 or just cut last 3 zeros to get it in seconds (which is used in PHP). Check Xero API's documentation for the format they use. – biesior Apr 16 '21 at 00:22
  • no i tried this as it not a timestamp as there are too many digits – atown99 Apr 16 '21 at 01:03

1 Answers1

1

A regular expression will extract this with ease:

$text = '/Date(1617667200000+0000)/';
preg_match('#^/Date\((\d{10})#', $text, $matches);  // Use # as delimiter.
                                                    // From start match /Date(
                                                    // match and capture next 10 digits

$dt = new DateTime('@'.$matches[1]);                // Create PHP DateTime object from unix timestamp

echo $dt->format('Y-m-d H:i:s');    // 2021-04-06 00:00:00

See https://3v4l.org/5jT5B

Edit - simpler version, no need for a regex if the data format is consistent

$text = '/Date(1617667200000+0000)/';
$timeStamp = substr($text, 6,10);
$dt = new DateTime('@'.$timeStamp);                // Create PHP DateTime object from unix timestamp

echo $dt->format('Y-m-d H:i:s');    // 2021-04-06 00:00:00
  • great solution! However in cakephp this code isnt working as the datetime object doesnt exists, there must be a workaround https://book.cakephp.org/3/en/core-libraries/time.html – atown99 Apr 16 '21 at 02:25
  • this works so its not a big deal, debug(date('Y-m-d',$matches[1])); great solution – atown99 Apr 16 '21 at 02:33
  • DateTime exists in every version of PHP since 5.2. See https://www.php.net/manual/en/class.datetime.php If you're on a version that doesn't have it you should be upgrading as a matter of urgency. – Tangentially Perpendicular Apr 16 '21 at 03:27