PHP日期 - 字符串到时间戳

时间:2011-10-21 20:56:13

标签: php date

我试图解析日期字符串而不必操纵字符串并期望给定格式。

我希望我的用户能够输入January 2, 20111-2-11,并最终以2011-01-02 12:00:00结束以保存在数据库中。

目前,我已经实现了这一目标:

$post_date = date("Y-m-d H:i:s", strtotime(stripslashes($_POST['post_date'])));

但似乎strtotime返回0,因为日期时间最终为1969-12-31 17:00:00

我需要改变什么?


更新

来自php.net:

(PHP 4,PHP 5)

strtotime - 将任何英文文本日期时间描述解析为Unix时间戳。

..我猜不是!


我不想尝试strtotime(数组:

if(isset($_POST['post_date'])){
                foreach($_POST['post_date'] as $id => $post_date){
                    print $post_date.'<br />';
                    if(strlen(trim($post_date)) && $post_date !== 'Date posted'){
                        $update_data[$id]['post_date'] = date("Y-m-d H:i:s", strtotime(stripslashes($post_date)));
                    }
                }
            }

使用它:

if(isset($_POST['post_date'])){
                foreach($_POST['post_date'] as $id => $post_date){
                    print $post_date.'<br />';
                    if(strlen(trim($post_date)) && $post_date !== 'Date posted'){
                        $post_date = str_replace(',', '', $post_date);
                        $post_date = str_replace('-', '/', $post_date);
                        $update_data[$id]['post_date'] = date("Y-m-d H:i:s", strtotime(stripslashes($post_date)));
                    }
                }
            }

感谢多位贡献者。我删除逗号并用正斜杠替换连字符。

3 个答案:

答案 0 :(得分:4)

OP的评论说:

  

$ _ POST ['post_date']实际上是一个数组(更新多个记录),   但一个示例值将是“2012年12月31日”

您不能在strtotime参数旁边传递逗号,这样做会始终返回1970-01-01 00:00:00。您必须删除用户生成的逗号。

$post_date = date("Y-m-d H:i:s", strtotime(stripslashes("1 January 1927 17:59")));
echo $post_date; //1927-01-01 17:59:00

答案 1 :(得分:2)

你真的需要关注你的意见,但这是一个想法。

foreach($_POST['input'] as $userDate) {
    // strtotime() will assume m/d/y or y-m-d depending on if '-' of '/' is used.
    $userDate = str_replace('-', '/', $userDate);
    $post_date = date("Y-m-d H:i:s", strtotime(stripslashes($userDate)));
}

答案 2 :(得分:1)

在PHP 5.3.3+(可能还有旧版本)中

date('Y-m-d', strtotime('January 2, 2011'))

(注意那里的逗号就是)会给你2011-01-02

但是,当您在该日期短语的末尾添加小时和分钟时,strtotime会返回0.

date('Y-m-d', strtotime('January 2, 2011 14:30'))

很遗憾给你1970-01-01 00:00:00 注意:http://codepad.org/qgJIJSaw

考虑删除逗号:

$date = str_replace(',', '', $date);

此外,strtotime会将'1-2-11'转换为2001 - 02 - 11(2001年2月11日),所以你可能需要重新排列数字,如果它们符合模式,使用类似的东西:

 $date = preg_replace('#^([\d]{1,2})-([\d]{1,2})-([\d]{2,4})$#', '$3-$1-$2', $date);
相关问题