masber
masber

Reputation: 3067

how to convert string to date or datetime in php

my PHP script is receving "/Date(1403071826510)/" as a JSON date. How can I convert this to PHP Date or DateTime?

this is what I am doing:

$milliseconds = (int) preg_replace("/[^0-9 ]/", '', $strDate);
return json_encode(Date('d/m/Y h:m',$milliseconds/1000));

but my casting is returning 2147483647 instead of 1403071826510 because my OS is 32 bits.

Any idea how to get the Date or DateTime from the string received?

thanks

Upvotes: 1

Views: 1299

Answers (3)

user1864610
user1864610

Reputation:

There's really no need for a regex here. You can simply extract the seconds from the middle of the string and work with that:

$sec =substr("/Date(1403071826510)/", 6, 10);
$dt = date("Y-m-d H:i:s",$sec);                // 2014-06-18 06:10:26

Mindful of @zamnuts comment here's a regex version that handles early dates:

preg_match('#Date\(([0-9]{0,10}?)([0-9]{1,3}\))#',"/Date(1403071826510)/",$matches);
$dt = date("Y-m-d H:i:s", $matches[1]);

Upvotes: 2

zamnuts
zamnuts

Reputation: 9582

Marc B's answer works just fine (+1), but for completeness (and since I already did the work), I was thinking to use the BC Math extension for PHP, which must be installed and is not included by default. BC Math allows PHP to work with arbitrarily large numbers.

Consider the following:

$input = '/Date(1403071826510)/';

$ms = preg_replace('/[^0-9 ]/','',$input);
var_dump($ms); // string '1403071826510' (length=13)

$sec = bcdiv($ms,'1000');
var_dump($sec); // string '1403071826' (length=10)

$date = Date('d/m/Y h:m',$sec);
var_dump($date); // string '17/06/2014 11:06' (length=16)

All conversions use String. Divide the parsed milliseconds using bcdiv by '1000' and pass that into Date for the seconds timestamp.

Upvotes: 1

Marc B
Marc B

Reputation: 360562

Strip off the milliseconds BEFORE you convert. Since it's a string, you just lop off the last 3 digits using substr(), and then cast to int

$js_timeval = '1403071826510';
$php_timeval = (int)substr($js_timeval, 0, -3); // 1403071826
echo date('r', $php_timeval);

Wed, 18 Jun 2014 00:10:26 -0600

Upvotes: 3

Related Questions