将字符串转换为 UNIX 时间戳
我正在尝试将字符串 11/24/2011 @ 01:15pm
转换为 UNIX 时间戳。格式为 mdY @ h:ia
我似乎无法让 strtotime
处理该字符串。有没有办法反转数据功能?我唯一的选择是创建一个新的非默认 php 函数来转换字符串吗?
服务器运行 CentOS 5、Apache 2.2 和 PHP 5.2.17。
I'm trying to convert the string 11/24/2011 @ 01:15pm
to a UNIX timestamp. The format is m-d-Y @ h:ia
I can't seem to get strtotime
to work with the string. Is there a way to reverse the data function? Is my only choice to create a new non-default php function to convert the string?
The server is running CentOS 5, Apache 2.2 and PHP 5.2.17.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用更现代的
DateTime
类(所以只要您使用 >= 5.3)。键盘。
Use the more modern
DateTime
class (so long as you're using >= 5.3).CodePad.
在 PHP 5.2 下,您可以使用
strptime
来解析具有特定日期时间字符串格式,然后使用mktime
将结果转换为时间戳。这应该被抽象为一个函数,可能有两个:
对解析句点缩写的支持似乎因操作系统而异。如果上述方法在特定操作系统上不起作用,请尝试使用“%P”而不是“%p”或通过
strtoupper
传递时间字符串(或两者)。以下内容应该适用于任何操作系统,但最好让strptime
来处理整个解析,因为以下内容不太适合作为通用strptimestamp
函数的基础。Under PHP 5.2, you can use
strptime
to parse a date-time string with a specific format, then usemktime
to convert the result to a timestamp.This should be abstracted as a function, possibly two:
Support for parsing the period abbreviation appears to vary from OS to OS. If the above doesn't work on a particular OS, try "%P" instead of "%p" or pass the time string through
strtoupper
(or both). The following should work under any OS, though it's preferable to getstrptime
to handle the entirety of the parsing, as the following is less suitable as the basis for a genericstrptimestamp
function.如果将“@”替换为空格,那么 strtotime 应该能够本地理解它。
输出:
If you replace the ' @ ' with a space, then strtotime should be able to understand it natively.
Output:
区分大小写可能是您的问题 http://php.net/manual/en/datetime.formats .php。
也许首先通过
strtoupper()
运行 $x,然后str_replace('@', '', $x)
(注意它用空字符串替换 @),然后尝试 <代码>strtotime()。希望这有帮助。Case sensitivity may be your issue http://php.net/manual/en/datetime.formats.php.
Perhaps run $x through
strtoupper()
first thenstr_replace('@', '', $x)
(notice it's replacing @ with an empty string), then trystrtotime()
. Hope this helps.这将替换您尝试转换为 strtotime 可接受的格式的时间字符串中的字符串部分。您始终可以将更多要替换的字符串部分添加到数组中。
此外,您不需要为此拥有最新的 php。
输出:
this will replace the parts of the string in the time string you are trying to convert into a format that is acceptable to strtotime. You can always add more string parts you want to replace to the arrays.
Also you dont need to have latest php for this.
Output: