我需要将字符串转换为日期格式,但它返回奇怪的错误。该字符串是这样的:在PHP中将特定的字符串转换为时间
21 nov 2012
我用:
$time = strtotime('d M Y', $string);
PHP返回的错误:
Notice: A non well formed numeric value encountered in index.php on line 11
缺少什么我在这里?
我需要将字符串转换为日期格式,但它返回奇怪的错误。该字符串是这样的:在PHP中将特定的字符串转换为时间
21 nov 2012
我用:
$time = strtotime('d M Y', $string);
PHP返回的错误:
Notice: A non well formed numeric value encountered in index.php on line 11
缺少什么我在这里?
你调用该函数完全错误的。只是通过它
$time = strtotime('21 nov 2012')
第二个参数是传递时间戳,新时间是相对的。它默认为time()
。
编辑:这将返回一个unix时间戳。如果您想要格式化它,请将新时间戳传递给date
函数。
您正在使用错误的功能,strtotime
只返回自epoch以来的秒数,它不会格式化日期。
尝试做:
$time = date('d M Y', strtotime($string));
最初,-1是因为尝试获得极差的FGITW答案.Downvote停留是因为它不回答问题。 – NullUserException
@NullUserException对不起。我正在打字,它提交了...... – Neal
你所有的代码都会把输入的字符串吐出来作为'2012年11月21日',这不是特别有用。 OP似乎想要一种可用于计算而不是演示的日期格式。 – Sammitch
为日期字符串转换为不同的格式:
<?php echo date('d M Y', strtotime($string));?>
strtotime
解析字符串返回所代表的UNIX时间戳。 date
将UNIX时间戳(或当前系统时间(如果未提供时间戳记)转换为指定的格式。因此,要重新格式化日期字符串,您需要将其传递给strtotime
,然后将返回的UNIX时间戳作为date
函数的第二个参数传递。 date
的第一个参数是所需格式的模板。
Click here了解有关日期格式选项的更多详细信息。
对于更复杂的字符串,使用:
$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();
你应该看看['日期时间:: createFromFormat()'](http://www.php.net/manual/en/datetime.createfromformat。 PHP);例如:http://codepad.viper-7.com/0b0edk。这使您可以精确设置您期望的格式,从strtotime()对美式mm-dd格式日期的无意义解析中拯救你 - 如果你仔细想想,它将成为一种非人道的愚蠢格式。 – NullUserException