在PHP中将特定字符串转换为时间

时间:2012-11-30 17:58:27

标签: php date strtotime

我需要将字符串转换为日期格式,但它返回一个奇怪的错误。字符串是这样的:

21 nov 2012

我用过:

$time = strtotime('d M Y', $string);

PHP返回错误:

Notice:  A non well formed numeric value encountered in index.php on line 11

我在这里缺少什么?

4 个答案:

答案 0 :(得分:8)

你完全错误地调用了这个函数。传递它

$time = strtotime('21 nov 2012')

第二个参数用于传入新时间相对的时间戳。它默认为time()

编辑:这将返回一个unix时间戳。如果您想格式化它,请将新时间戳传递给date函数。

答案 1 :(得分:2)

将日期字符串转换为其他格式:

<?php echo date('d M Y', strtotime($string));?>

strtotime解析一个字符串返回表示的UNIX时间戳。 date将UNIX时间戳(或当前系统时间,如果未提供时间戳)转换为指定格式。因此,要重新格式化日期字符串,您需要将其传递给strtotime,然后将返回的UNIX时间戳作为date函数的第二个参数传递。 date的第一个参数是您想要的格式的模板。

Click here了解有关日期格式选项的更多详细信息。

答案 2 :(得分:0)

您使用了错误的功能,strtotime仅返回自纪元以来的秒数,它不会格式化日期。

尝试做:

$time = date('d M Y', strtotime($string));

答案 3 :(得分:0)

对于更复杂的字符串,请使用:

$datetime = DateTime::createFromFormat("d M Y H:i:s", $your_string_here);
$timestamp = $datetime->getTimestamp();
相关问题