简体   繁体   中英

Get and parse string from json to php

I got json response with the following format :

 "/Date(1234)/"

How do I get the numbers only as string (1234) in php ?

thanks

$dateonly = "/Date(1234)/";
echo $dateonly = preg_replace("/[^0-9,.]/", "",$dateonly);

I don't think this is JSON, or at least not a valid one. Nonetheless, you can extract numbers like this:

preg_match_all('!\d+!', stripslashes("/Date(1234)/"), $output);
echo $output;

This format /Date(1234)/ usually called JSON Date Format. It contain unixtime with miliseconds. So, when you extract the number you need to divide it to 1000 to get the unixtime and process it in PHP. Here I give a function to extract the date and convert it to PHP DateTime Object

function parseJSDate($jsDateObject)
{
    $dateTime = null;
    if (preg_match("/\/Date\((\d+)\)\//", $jsDateObject, $match)) {
        if (isset($match[1]) && is_numeric($match[1])) {
            $timestamp = (int) $match[1];
            $dateTime  = new \DateTime();
            $dateTime->setTimestamp($timestamp / 1000);
        }
    }

    return $dateTime;
}

$date = parseJSDate("/Date(1224043200000)/");
echo $date->format("Y-m-d H:i:s");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM