简体   繁体   English

如何在PHP中将字符串转换为日期或日期时间

[英]how to convert string to date or datetime in php

my PHP script is receving "/Date(1403071826510)/" as a JSON date. 我的PHP脚本正在将“ / Date(1403071826510)/”作为JSON日期。 How can I convert this to PHP Date or DateTime? 如何将其转换为PHP Date或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. 但我的转换返回2147483647而不是1403071826510,因为我的操作系统是32位。

Any idea how to get the Date or DateTime from the string received? 任何想法如何从接收到的字符串中获取Date或DateTime?

thanks 谢谢

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 由于它是一个字符串,因此您可以使用substr()将最后3位数字转换为int ,然后将其转换为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

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: 注意@zamnuts的评论,这是处理早期日期的正则表达式版本:

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

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. Marc B的答案很好(+1),但出于完整性考虑(并且由于我已经完成了工作),我一直在考虑对PHP使用BC Math扩展 ,该扩展必须已安装且默认情况下未包括在内。 BC Math allows PHP to work with arbitrarily large numbers. BC Math允许PHP处理任意数量的数字。

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 . 所有转换都使用String Divide the parsed milliseconds using bcdiv by '1000' and pass that into Date for the seconds timestamp. 使用bcdiv将解析的毫秒数除以'1000'然后将其传递给Date作为秒时间戳。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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