将此字符串转换为时间戳 PHP
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19346858/
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
Convert this string to timestamp PHP
提问by user2876368
I have this string: "13/10 15:00" and I would like to convert it to timestamp but when I do this:
我有这个字符串:“13/10 15:00”,我想将它转换为时间戳,但是当我这样做时:
$timestamp = strtotime("13/10 15:00");
It returns an empty value.
它返回一个空值。
回答by
In your code strtotime()
is attempting to convert 13/10
as the tenth day of the 13th month, which returns an error.
在您的代码strtotime()
中尝试转换13/10
为第 13 个月的第 10 天,这会返回错误。
If you want to parse a date string with a custom format, it's better to use DateTime::createFromFormat() instead:
如果要使用自定义格式解析日期字符串,最好使用 DateTime::createFromFormat() 代替:
$dtime = DateTime::createFromFormat("d/m G:i", "13/10 15:00");
$timestamp = $dtime->getTimestamp();
回答by Lajos Veres
$timestamp = strtotime("13-10-2013 15:00");
This can be important:
这可能很重要:
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.
To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible.
m/d/y 或 dmy 格式的日期通过查看各个组件之间的分隔符来消除歧义:如果分隔符是斜杠 (/),则假定为美国 m/d/y;而如果分隔符是破折号 (-) 或点 (.),则假定为欧洲 dmy 格式。
为避免潜在的歧义,最好尽可能使用 ISO 8601 (YYYY-MM-DD) 日期或 DateTime::createFromFormat()。