PHP将字符串转换为时间戳

时间:2015-07-13 01:54:35

标签: php timestamp

我正在处理一个代表这种格式的时间戳的字符串:

Mon Jul 13 11:32:00 EST 2015

我现在需要将其转换为时间戳,以此格式插入我的数据库:

MM/DD/YYYY HH:MM:SS

我通常会用这个:

date("m/d/Y h:i:s A", $timestamp)

但这不起作用。我不需要担心时区,因为时间戳已经在本地时区

2 个答案:

答案 0 :(得分:0)

您需要先将时间戳字符串转换为时间。如果您想忽略时区,可以执行以下操作:

// Set the time
$time = "Mon Jul 13 11:32:00 EST 2015";
// Cut out the timezone details
$time = str_replace(" EST", "", $time);
// Convert the string time into a time and then into a timestamp
$timestamp = date("m/d/Y h:i:s A", strtotime($time));
// echo $timestamp = "07/13/2015 11:32:00 AM"

或者,您可以使用类似mktime()(http://php.net/mktime)的内容,但这需要您将时间字符串拆分为单独的元素。

答案 1 :(得分:0)

只需两行代码。使用Datetime对象将使您的代码更清晰。

<?php
$datetime = new Datetime("Mon Jul 13 11:32:00 EST 2015");
print $datetime->format("m/d/Y h:i:s A");
相关问题