PHP:strtotime() 总是返回 01/01/1970

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10946457/
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-24 23:25:09  来源:igfitidea点击:

PHP : strtotime() returns always 01/01/1970

phpdateformatstrtotime

提问by HerrM

I am trying to display dates in the European format (dd/mm/yyyy)with strtotimebut it always returns 01/01/1970.

我试图在European format (dd/mm/yyyy)with 中显示日期,strtotime但它总是返回 01/01/1970。

Here is my codeline :

这是我的代码行:

echo "<p><h6>".date('d/m/Y', strtotime($row['DMT_DATE_DOCUMENT']))."</h6></p>";

In my database, the field is a varchar and records are formated like yyyy.mm.dd

在我的数据库中,该字段是一个 varchar 并且记录的格式类似于yyyy.mm.dd

I use the same codeline for another field that is formated like yyyy-mm-dd(varchar too) and it works fine.

我对另一个格式为yyyy-mm-dd(也是 varchar)的字段使用相同的代码行,它工作正常。

Thanks for your help.

谢谢你的帮助。

回答by flowfree

Since the format yyyy-mm-ddworks, try to replace .with -:

由于格式yyyy-mm-dd有效,请尝试替换.-

date('d/m/Y', strtotime(str_replace('.', '-', $row['DMT_DATE_DOCUMENT'])));

回答by fquffio

Try with:

尝试:

$date = date_parse_from_format("Y.m.d", $row['DMT_DATE_DOCUMENT']);
$time = mktime($date['hour'], $date['minute'], $date['second'], $date['month'], $date['day'], $date['year']);
echo "<p><h6>".date('d/m/Y', $time)."</h6></p>";

(Using date_parse_from_format()instead of strtotime())

(使用date_parse_from_format()代替strtotime()

Or just:

要不就:

$date = date_parse_from_format("Y.m.d", $row['DMT_DATE_DOCUMENT']);
echo "<p><h6>{$date['day']}/{$date['month']}/{$date['year']}</h6></p>";

回答by Subir Kumar Sao

Quoting from the strtotime page in the PHP manual.

引用自PHP 手册中的 strtotime 页面

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。

To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat()when possible.

为避免潜在的歧义,最好使用 ISO 8601 (YYYY-MM-DD) 日期或DateTime::createFromFormat()在可能的情况下。

So in your case it should either be in format YYYY-MM-DD or d.m.y.

所以在你的情况下,它应该是格式 YYYY-MM-DD 或 dmy

If you want to parse your custom format then use date_create_from_format

如果要解析自定义格式,请使用date_create_from_format

For example,

例如,

date_create_from_format('Y.m.d',$row['DMT_DATE_DOCUMENT'])