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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13650578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:50:54  来源:igfitidea点击:

Convert specific string to time in PHP

phpdatestrtotime

提问by Dênis Montone

I need to convert a string into date format, but it's returning a weird error. The string is this:

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

21 nov 2012

I used:

我用了:

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

PHP returned the error:

PHP 返回错误:

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

What am I missing here?

我在这里缺少什么?

回答by mpen

You're calling the function completely wrong. Just pass it

您完全错误地调用了该函数。只要通过它

$time = strtotime('21 nov 2012')

The 2nd argument is for passing in a timestamp that the new time is relative to. It defaults to time().

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

Edit:That will return a unix timestamp. If you want to then format it, pass your new timestamp to the datefunction.

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

回答by Rubin Porwal

To convert a date string to a different format:

要将日期字符串转换为不同的格式:

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

strtotimeparses a string returns the UNIX timestamp represented. dateconverts a UNIX timestamp (or the current system time, if no timestamp is provided) into the specified format. So, to reformat a date string you need to pass it through strtotimeand then pass the returned UNIX timestamp as the second argument for the datefunction. The first argument to dateis a template for the format you want.

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

Click herefor more details about date format options.

单击此处了解有关日期格式选项的更多详细信息。

回答by Joakim Ling

For more complex string, use:

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

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

回答by Naftali aka Neal

You are using the wrong function, strtotimeonly return the amount of seconds since epoch, it does not format the date.

您使用了错误的函数,strtotime只返回自纪元以来的秒数,它没有格式化日期。

Try doing:

尝试做:

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